jquery Button、Knockout.js 和 ajax 请求
我正在使用 knockout.js 和 jquery ui 按钮。我在下面的按钮上构建了一个自定义绑定。我正在更改点击项目上的文本,但我还有额外的点击提交 ajax 请求。请求完成后将文本设置回原始文本的最佳设计模式是什么?我知道我可以手动执行此操作,或者将被调用的元素传递给方法,但是是否有更解耦的方法。
<button type="submit" data-bind="button: { text: 'login', pressed: 'authenticating...' }, click: function() { site.ajaxRequest(); }"></button>
ko.bindingHandlers.button = {
init: function (element, valueAccessor) {
var binding = ko.utils.unwrapObservable(valueAccessor());
$(element).button({ label: binding.text }).click(function () {
$(this).button({ label: binding.pressed });
});
}
};
I am using knockout.js with jquery ui button. I built a custom binding on the button which is below. I am changing the text on the click item, but I also have additional click that submits an ajax request. What is the best design pattern to set the text back to the original text once the request is complete. I know I can do it manually or, pass the element being called to the method, but is there a more de-coupled way.
<button type="submit" data-bind="button: { text: 'login', pressed: 'authenticating...' }, click: function() { site.ajaxRequest(); }"></button>
ko.bindingHandlers.button = {
init: function (element, valueAccessor) {
var binding = ko.utils.unwrapObservable(valueAccessor());
$(element).button({ label: binding.text }).click(function () {
$(this).button({ label: binding.pressed });
});
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不建议将按钮绑定到硬编码文本。相反,我建议将 jQuery UI 按钮绑定到一个可观察对象,然后适当地更新该可观察对象:
第一个代码片段是一个绑定,可用于更新我使用的 jQuery UI 按钮。 (伪代码)
接下来,这是您的绑定的样子。这假设您的模型上有一个名为 textObservable 的可观察对象;
最后,在 ajaxRequest 方法中,在发出 AJAX 请求之前,您需要将 textObservable 更新为“Authenticating”。在 ajax 调用的成功处理程序中,您需要将 textObservable 更新为初始值。
I wouldn't recommend binding the button to hardcoded text. Instead, I recommend binding the jQuery UI button to an observable and then updating that observable appropriately:
First snippet is a binding that can be used to update a jQuery UI button that I use. (psuedo code)
Next, here is what your binding would look like. This assumes you have an observable on your model called textObservable;
Finally, in your ajaxRequest method, before you make the AJAX request, you need to update textObservable to 'Authenticating'. In the success handler of the ajax call, you need to update textObservable to your initial value.