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);
});
}
};
}]);
因此,如果模型的值发生变化,那么使用 $watch 注册以监听模型变化的处理程序将被执行,因此,widget 的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?
推荐答案
我建议实施 ctrl.$render()
而不是 scope.$watch()
.仅当 Angular 内部的某些内容更改模型时才应调用 $render.小提琴示例.
Instead of scope.$watch()
, I suggest implementing ctrl.$render()
. $render should only be called if something inside Angular changes the model. Fiddle example.
这解决了您没有提到的问题.不幸的是,它并没有解决您提到的问题.在小提琴中,绑定了一个 blur
事件,而不是一些 widget.on() 事件.也许这对你有用–即,仅在模糊时更新模型,而不是在每次击键时更新模型(但是,这假设您的小部件接受击键).
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).
也许您还可以要求小部件作者提供一个不会触发事件的设置"方法.然后可以在 $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屋!