AngularJS指令 - 最佳实践使用ngModel时使用jQuery插件 [英] AngularJS directives - best practices when using ngModel with jQuery widget
问题描述
下面是我的问题。例如,我们有以下的指令,它在后台使用一些jQuery插件:
Here is my problem. For example, we have the following directive, which uses some jQuery widget behind the scenes :
module.directive('myWidget', [function() {
return {
require: "ngModel",
restrict: "A",
replace: true,
templateUrl: "templates/myWidget.html",
link: function(scope, element, attrs, ctrl) {
element.widget_name().on('value_updated', function(event) {
scope.$apply(function() {
var newModelValue = event.some_value;
ctrl.$setViewValue(newModelValue);
});
});
scope.$watch(attrs["ngModel"], function(value){
element.widget_name('set_value', value);
});
}
};
}]);
因此,如果模型的值发生变化,那么这是使用$手表监听模型改变注册的处理程序将被执行,并且,因此,部件的SET_VALUE'方法也将被执行。这意味着,value_updated事件将被触发。
So, if model's value changes, then the handler which is registered using $watch to listen for changes in model will be executed, and, consequently, widget's 'set_value' method will be executed too. This means that 'value_updated' event will be triggered.
我的问题是:什么是最好的做法来实现指令类似的行为,以避免DOM事件处理程序和观察家的额外通话
My question is: what is the best practice to implement similar behavior in directives to avoid extra calls of DOM event handlers and watchers?
推荐答案
而不是范围。$表()
,我建议实施控制。 $渲染()
。 $渲染如果里面的东西角改变模型只应调用。 小提琴例如。
Instead of scope.$watch()
, I suggest implementing ctrl.$render()
. $render should only be called if something inside Angular changes the model. Fiddle example.
这解决了你没有提到的一个问题。不幸的是,它并没有解决你没有提的问题。在小提琴,一个模糊
事件的约束,而不是某些widget.on()事件。也许这会为你工作&ndash的;即,只更新模糊的模型,而不是每个按键(然而,这假设你的小部件接受击键)。
This solves a problem you did not mention. Unfortunately, it does not solve the problem you did mention. In the fiddle, a blur
event is bound, rather than some widget.on() event. Maybe that would work for you – i.e., only update the model on blur, rather than every keystroke (this assumes your widget is accepting keystrokes, however).
也许你也可以要求widget作者提供不触发事件的一个套的方法。然后,可以在$使用render()方法。
Maybe you could also ask the widget author to provide a "set" method that does not trigger an event. Then that could be used in the $render() method.
这篇关于AngularJS指令 - 最佳实践使用ngModel时使用jQuery插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!