我正在创建一个基于jQuery UI范围滑块的计算器,并且有一个可行的设置。我的应用程序中有一个bindEvents函数,它将滑块绑定到slide
事件:
// this is where I bind all slide events
bindEvents: function() {
// hold on to the value of this
var self = CloudCalc;
// bind the slider's slide event to a data event
self.sl.on('slide', this.setSliderOutputValue);
}
然后这是忠实执行我的事件的处理程序:
setSliderOutputValue: function (event, ui) {
// hold on to the value of this
var self = CloudCalc;
// show the ui output value on slide event
self.output.html( ui.value + " INSTANCE");
}
现在我想在用户滑动滑块时触发多个事件。所以我想在这个设置中使用观察者模式(使用addyosmani的pubsub插件):
bindEvents: function() {
// hold on to the value of this
var self = CloudCalc;
// bind the slider's slide event and publish it
self.sl.on('slide', $.publish('slider/moved'));
}
以下是订阅:
subscriptions: function () {
$.subscribe('slider/moved', this.setSliderOutputValue);
}
因此,当此订阅调用setSliderOutputValue
事件时,我收到控制台错误消息:
Uncaught TypeError: Cannot read property 'value' of undefined
这意味着对ui属性的引用未传递给setSliderOutputValue
事件。
如何传递ui属性?如果我做错了,请纠正我。
答案 0 :(得分:0)
所以这就是我使用pubsub模式的方法。我将$.publish
调用添加到setSliderOutputValue
方法,如下所示:
setSliderOutputValue: function (event, ui) {
// hold on to the value of this
var self = CloudCalc;
// show the ui output value on slide event
self.output.html( ui.value + " INSTANCE");
$.publish('slider/moved')
},
然后添加到我的订阅中:
subscriptions: function () {
$.subscribe( 'plan/results', this.parseJSON );
$.subscribe( 'slider/moved', this.setVMval );
$.subscribe( 'slider/moved', this.setRAMval );
$.subscribe( 'slider/moved', this.setHDval );
},
瞧!我现在可以使用我的jQuery范围滑块基于单个事件监听并触发多个事件。
欢迎通过将多个订阅调用重构为单个调用来改进此代码的任何建议。