在通过 $.request 或其他方法添加新元素后,October 在页面上触发“渲染”事件。
所以,你最好听:
$(window).on('render', function() {
$('input').on('keypress', function(e){
}
});
唯一的问题是,事情会得到“双重”按键。
为此,october 建议使用基础框架模式。这样,如果页面上已经存在一个元素,事件监听器只会被绑定一次并且不会重复。
https://octobercms.com/docs/ui/foundation
+function ($) { "use strict";
var Base = $.oc.foundation.base,
BaseProto = Base.prototype
var SomeDisposableControl = function (element, options) {
this.$el = $(element)
this.options = options || {}
$.oc.foundation.controlUtils.markDisposable(element)
Base.call(this)
this.init()
}
SomeDisposableControl.prototype = Object.create(BaseProto)
SomeDisposableControl.prototype.constructor = SomeDisposableControl
SomeDisposableControl.prototype.init = function() {
this.$el.on('click', this.proxy(this.onClick))
this.$el.one('dispose-control', this.proxy(this.dispose))
}
SomeDisposableControl.prototype.dispose = function() {
this.$el.off('click', this.proxy(this.onClick))
this.$el.off('dispose-control', this.proxy(this.dispose))
this.$el.removeData('oc.someDisposableControl')
this.$el = null
// In some cases options could contain callbacks,
// so it's better to clean them up too.
this.options = null
BaseProto.dispose.call(this)
}
SomeDisposableControl.DEFAULTS = {
someParam: null
}
// PLUGIN DEFINITION
// ============================
var old = $.fn.someDisposableControl
$.fn.someDisposableControl = function (option) {
var args = Array.prototype.slice.call(arguments, 1), items, result
items = this.each(function () {
var $this = $(this)
var data = $this.data('oc.someDisposableControl')
var options = $.extend({}, SomeDisposableControl.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('oc.someDisposableControl', (data = new SomeDisposableControl(this, options)))
if (typeof option == 'string') result = data[option].apply(data, args)
if (typeof result != 'undefined') return false
})
return result ? result : items
}
$.fn.someDisposableControl.Constructor = SomeDisposableControl
$.fn.someDisposableControl.noConflict = function () {
$.fn.someDisposableControl = old
return this
}
// Add this only if required
$(document).render(function (){
$('[data-some-disposable-control]').someDisposableControl()
})
}(window.jQuery);
我建议阅读上面的链接,因为它解释了很多问题等等......以及为什么清理很重要。
就个人而言,我在 10 月的基础上进行了扩展,以使“清理”和管理变量更容易。
https://github.com/tschallacka/october-foundation/blob/master/src/october-foundation-base.js
基本上它的作用是确保函数自动解除绑定,在通过 jquery 命令从 dom 中删除元素时清除变量,并在触发 'render' 事件时自动绑定到标记元素。
使用我的脚本,它会变成:
// ..... foundation code
Application.prototype.handlers = function(type) {
this.bind('keypress',this.$el, this.keypressHandler);
};
Application.prototype.init = function() {
/**
* example;
*/
this.alloc('foobar',42);
console.log(this.foobar);
}
Application.prototype.keypressHandler = function(e) {
if(!e.defaultPrevented) {
// only numbers
if ( charCode < 48 || charCode > 57 ) {
e.preventDefault();
return false;
}
return true;
}
}
// foundation code ....