MVC场景中的Javascript事件与回调 [英] Javascript Events vs. Callbacks In MVC Scenario

查看:72
本文介绍了MVC场景中的Javascript事件与回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力找到一种很好的方法来获得视图和控制器并最小化它们之间的联系。

I'm trying to work out a nice way to have views and controllers and minimize the ties between them.

除了一个事件的多个订阅者之外,还有像这样的js代码之间的任何主要区别:

Aside from multiple subscribers to one event, is there any major difference between js code like this:

var customers = {
    get: function(callback) {
        $.get('/customers', {}, function(data) { 
            callback.call(this, data); 
        });
    }
};

这样的事件驱动方法(事件对象只是伪代码):

And an event-driven approach like this (event object is just pseudo code):

var customers = {
    get: function() {
        $j.get('/customers', {}, function(data) { 
            event.publish('customers.loaded', data); 
        });
    }
};

在这两种情况下,客户对象的消费者都不知道其内部工作原理。一种方式比另一种方式有优势吗?

In both cases, the consumer of the customers object is ignorant of its inner workings. Does one way have an advantage over the other?

推荐答案

事件的回调,但区别在于他们何时何地受到约束。在第一种情况下,您需要在调用 get 时引用回调,此外它仅限于单个回调。

Event's are callbacks, but the difference is when and where they're bound. In the first case, you need to have a reference to the callback at the time that get is called, additionally it's limited to a single callback.

在第二种情况下,(假设您正在触发具有该伪代码的事件),您可能已将回调限制在<$ c $的范围之外调用c> get ,允许更强大的数据封装。此外,事件支持触发多个回调,因此可以执行不同的功能,具体取决于有权访问 customers 对象。

In the second scenario, (assuming you're triggering an event with that pseudo-code) you could have bound a callback outside of the scope of where get is called, allowing for stronger data-encapsulation. Additionally, events support triggering multiple callbacks, so that different functions can be executed depending on what has had access to the customers object.

我建议使用面向事件的解决方案,因为JavaScript是一种面向事件的语言。

I'd recommend going with the event-oriented solution as JavaScript is an event-oriented language.

这篇关于MVC场景中的Javascript事件与回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆