إنشاء البرنامج المساعد مسج ، كيف أفعل مخصص المبينات ؟
سؤال
وأود أن إنشاء البرنامج المساعد مسج مع API شيئا من هذا القبيل:
$("#chart").pluginName().attr("my_attr");
بدلا من هذه:
$("#chart").pluginName_attr("my_attr");
$.pluginName.attr("#chart", "my_attr");
في الأساس, بدلا من الاضطرار إلى مساحة كل طريقة على أن أعمال مشابهة لتلك التي في مسج, أود أن "نطاق" أساليب مخصص api ، حيث $("#chart).pluginName()
سيعود كائن من النوع الذي get
, attr
, find
, و قليل من الآخرين أن تكون إعادة كتابة تماما.
أنا متأكد من أن هذا ليس محبوب الفكرة كما يكسر الاتفاقية (يفعل ذلك؟) ، لكنه أسهل وأكثر قابلية للقراءة ، وربما أكثر الأمثل ، من الخيارين أعلاه.ما هي أفكارك ؟
المحلول
أنا تجريب هذه الفكرة.
يبدو أنك يمكن أن مجرد تعديل وظائف الكائن مسج أن المساعد يتلقى والعودة ذلك.
شيء من هذا القبيل:
$.fn.tester = function() { // The plugin
this.css = function() { // Modify the .css() method for this jQuery object
console.log(this.selector); // Now it just logs the selector
return this; // Return the modified object
}
return this; // Return the modified object
}
http://jsfiddle.net/EzzQL/1/ (تحديث من الأصلي إلى الكتابة .html() وكذلك)
$.fn.tester = function() {
this.css = function() {
console.log(this.selector); // This one logs the selector
return this;
}
this.html = function() {
alert(this.selector); // This one alerts the selector
return this;
}
return this;
};
// Because .css() and .html() are called after .tester(),
// they now adopt the new behavior, and still return a jQuery
// object with the rest of the methods in tact
$('#test1').tester().css().html().animate({opacity:.3});
// .css() and .html() still behave normally for this one
// that doesn't use the plugin
$('#test2').css('backgroundColor','blue').html('new value');
تحرير:
بدلا من ذلك, إذا كنت تريد الذهاب إلى ذاكرة التخزين المؤقت إلى العناصر التي العرف يجب أن تطبق أساليب ، يمكن أن .apply()
الطرق قبل استخدامها.
بناء على المثال أعلاه:
var $test1 = $('#test1'); // Cache the elements
$.fn.tester.apply($test1,[this]); // apply() the new methods
$test1.css().html().animate({opacity:.3}); // Use the new methods