3. 部件事件和属性
1)事件
部件类似现有大部分图形用户界面库(Qt, GTK, Swing,...)那样,触发事件,
处理事件。例如:
instance.oepetstore.ConfirmWidget = instance.web.Widget.extend({
start: function() {
var self = this;
this.$el.append("<div>Are you sure you want to perform this action?</div>" +
"<button class='ok_button'>Ok</button>" +
"<button class='cancel_button'>Cancel</button>");
this.$el.find("button.ok_button").click(function() {
self.trigger("user_choose", true);
});
this.$el.find("button.cancel_button").click(function() {
self.trigger("user_choose", false);
});
},
});
instance.oepetstore.HomePage = instance.web.Widget.extend({
start: function() {
var widget = new instance.oepetstore.ConfirmWidget(this);
widget.on("user_choose", this, this.user_choose);
widget.appendTo(this.$el);
},
user_choose: function(confirm) {
if (confirm) {
console.log("The user agreed to continue");
} else {
console.log("The user refused to continue");
}
},
});
注意:var self = this;请记住,在 JavaScript 中,变量 this 会隐含传递给所有函数。如果函数像对象引用方法那么用,通过 this 我们知道当前的对象是什么。每个已声明的函数都有自己的 this。所以,当我们在一个函数内声明了另一个函数,这个新功能将有自己的 this ,这和父函数 this 含义不同。如果我们要用原来的对象 this ,最简单的方法是把引用存储在一个本地变量。在 OpenERP 内,按照 Python 的习惯,通常该变量命名为 self。
由于这个部件应该是通用的,它本身不应执行任何具体 action。所以,我们用 trigger() 方法设置了名字叫"user_choose"的触发器和事件。
Widget.trigger(event_name [ , ...]) 方法的第一个参数是待触发的事件名,也接受任何数量的其他参数。这些参数将被传递到所有的事件侦听器。
然后,我们修改部件HomePage去实例化一个部件ConfirmWidget,通过on( )方法监听"user_choose"事件。Widget.on(event_name,object, func) 允许绑定一个事件 event_name 触发时调用的函数func。如果func是个方法,则object是func函数的引用关联对象。当func被调用时,trigger()的其他参数会传递给它。例如:
start: function() {
var widget = ...
widget.on("my_event", this, this.my_event_triggered);
widget.trigger("my_event", 1, 2, 3);
},
my_event_triggered: function(a, b, c) {
console.log(a, b, c);
// will print "1 2 3"
}
2)属性
属性类似与普通对象的属性。可以在对象上设置数据,但有个额外的功能:属性值改变时将触发事件。
start: function() {
this.widget = ...
this.widget.on("change:name", this, this.name_changed);
this.widget.set("name", "Nicolas");
},
name_changed: function() {
console.log("The new value of the property 'name' is", this.widget.get("name"));
}