2
상태를 유지해야하는 jQuery
플러그인을 작성했습니다. 페이지에는 여러 인스턴스가 있지만 각 인스턴스에는 데이터베이스의 키와 연관된 다른 데이터가 있습니다. jQuery 사이트의 예제를 시작점으로 사용하려고하지만 몇 가지 어려움이 있습니다. 여기서 'hid'와 'hnid'는 내가 관심있는 핵심 가치입니다. 프로덕션에서는 옵션을 통해 전달할 것입니다. 하지만 여기에 내 질문은 저장 버튼을 클릭하고 '저장'방법을 실행하면 내 데이터 키, 숨김 및 숨기기를 어떻게 얻을 수 있습니까? 이제 코드를 실행할 때 데이터에 대해 null을 얻습니다.jquery 플러그인으로 상태를 유지 하시겠습니까?
(function($) {
var settings = {
'background-color': 'blue'
};
var saveData = function() {
var data = $(this).data('inknote');// now this refers to save button so has no 'data' associated with it.
console.log('data', data);
}
var methods = {
init: function(options) {
return this.each(function() {
if (options) {
$.extend(settings, options);
}
var $this = $(this),
data = $this.data('inknote');
// If the plugin hasn't been initialized yet
if (!data) {
var startData = {
target: $this,
hid: 1,
hnid: 2
};
$this.data('inknote', startData);
}
var $messageDiv = $('<div>').addClass('messages').html(' ');
/* am I calling the save method properly here ?*/
var $saveButton = $('<input>').attr('type', 'button').attr('value', 'Save').bind('click', function() { methods['save'].apply(this); });
var $printButton = $('<input>').attr('type', 'button').attr('value', 'Print').bind('click', function() { methods['print'].apply(this); });
var $lockStatus = $('<div>').addClass('lock').addClass('unlocked').html(' ');
$this.append($messageDiv).append($saveButton).append($printButton).append($lockStatus);
});
},
save: function(el) {
return $(this).each(function() {
saveData(this);
});
},
print: function(el) {
return false;
}
};
$.fn.inknote = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.inknote');
}
};
})(jQuery);
답변을 제공해 주셔서 감사합니다. 그것은 올바른 방향으로 갈거야. 코드를 통해 데이터 항목이 특정 dom 요소에 연결되어야한다는 것을 명확하게 나타 냈습니다. 또한 클릭 이벤트가 플러그인에 첨부 된 원래 요소에서 전달 된 방식입니다. 방금 데이터 "캡슐화"를 플러그인 내부로 이동하고 설정을 통해 키를 전달했습니다. http://jsfiddle.net/voam/uJnQj/ – voam
도움이 된 것을 기쁘게 생각합니다! – ifaour
-1 : 나는 좋은 옛날을 알고있다. 그러나 어쨌든 : [Link-Only Answer는 좋은 대답이 아니다.] (http://meta.stackexchange.com/q/225370) (ifaour는 고백을하지만 그는 그 질문을 완전히 이해하지 못했다) –