我想要实现的是构建一个在元素上执行 验证逻辑 的插件,但我想继续使用下一个链式方法,但是如果它不行,停止并中止下一个链条。
例如,我有这个
;(function($, window, document, undefined) {
var pluginName = 'check';
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
}
function Plugin(element, options) {
// Do the logic here
}
})(jQuery, window, document);
因此,为了在回调后继续使用链接,您必须返回 this ,就像我在上面的插件中所做的那样。
jQuery( document ).ready( function($) {
button.check().on( 'click', function(){
// do something
});});
但是如果我只想满足检查功能逻辑条件,我想执行点击功能。
答案 0 :(得分:1)
您可以使用Object.freeze()
创建普通对象,以防止更改对象的属性;将对象分配给插件中的$._data(this[0]).events
,以便不允许在元素"events"
对象上编写$._data()
属性。
;
(function($) {
$.fn.check = function(type, conditions) {
const el = this;
let condition = conditions || el[0].tagName === "DIV";
// if element `.tagName` is `"DIV"` do not set events
if (condition && !type) {
if (!$._data(el[0])["events"]) {
let e = Object.defineProperty(new Object(), "events", {
value: null
});
Object.freeze(e);
$._data(el[0]).events = e
return el
}
}
if (type && type === "bool") {
return condition
}
if (type && type === "delete") {
$._data(el[0]).events = null;
return this
}
}
})(jQuery);
$(function() {
console.log("check called, do not attach events, try clicking DIV");
$("div").check().on("click", function(e) {
console.log(this)
})
.on("mouseover", function(e) {
console.log(this)
});
// boolean
console.log("check boolean:", $("div").check("bool"));
console.log("allow events in ten seconds");
setTimeout(function() {
// delete
console.log("check delete:", $("div").check("delete")[0].tagName);
console.log("click DIV");
$("div").on("click", function(e) {
console.log(this)
});
}, 10000)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>click</div>
&#13;