2012-02-09 75 views
0

我第一次尝试Spine.js,并且当前正在转换使用jQuery的现有js文件。使用Spine&jQuery绑定到全局事件

目前,它确实是这样的:

$('document').bind('facebook:ready', function() { 
    $('.myElement').click(callback); 
}); 

凡基本上等待的Facebook:准备好'事件要在文档触发,然后附加一个onclick到.myElement。

到目前为止,我已经能够通过以下对控制器的文档做定期的活动,http://spinejs.com/docs/controllers

myController = Spine.Controller.sub({ 
    el: $('#mainViewElement') 
    , events: hashOfEventsToNamesAndHandler 
}); 

什么是旧的代码转换为脊柱的正确方法?而且,作为一个相关的问题,由于我有一个用于命名空间的全局对象,最好是将我的'facebook:ready'事件添加到文档而不是文件中?


我在想的一件事是我可以在'脸书:准备好'时触发一个标志。然后,我使用正常的Spine.Controller语法将点击处理程序附加到.myElement,当点击被触发时,我检查是否设置了该标志,如果没有,我立即返回。我只是不确定这是否是最好的方式去做这件事......

回答

1

facebook:ready事件是发生在Spine之外的事情,所以你将无法使用事件散列来处理它。事件散列中的操作范围限定在控制器处于活动状态的元素上。

在Spine中,您不仅限于事件属性。你可以使用任何你想要的。事件散列只是一个捷径。要设置更复杂的东西,你可以在构造函数中做一些事情。

我不知道您的应用程序的层次结构,以及在facebook事件触发时有多少控制器需要更新自身。但是,让我们假设只有一个控制器会监控它,并告知其他人发生了什么......以防其他逻辑需要被触发。

class FacebookIntegrationController extends Spine.Controller 

    constructor: -> 
    super 

    # You can't use $ here because that is scoped to the current @el. So use the jQuery object itself. 
    # What I would suggest is to just trigger a local action. 
    jQuery('document').bind('facebook:ready', @facebookReady()) 

    facebookReady: (argument) => 
    # Here you can just handle it however you would like. 

    # This works if .myElement is somewhere in the @el of this controller. But it isn't the nicest solution. 
    $('.myElement').click(callback) 

    # Instead write the code that's in the callback in this function. Or if the callback is passed along with the original event you can get to it as the arguments are passed along to the function (argument in this case). 

    # If multiple controllers need to take action after the facebook:ready event has fired in the document you could also trigger a new event: 
    @trigger('facebook:ready') # You could add optional arguments to trigger that get passed along to the functions that bind to it. 

    # Other controllers or other Spine classes could listen for it by using: 
    # FacebookIntegrationController.bind('facebook:ready', @localActionToTrigger) 
    # If this doesn't work nicely for you you could also use global events by replacing @trigger with Spine.trigger and Spine.bind('facebook:ready', @localActionToTrigger) 

未经测试的代码! 编辑:执行代码:http://jsfiddle.net/SpoBo/zAwKk/3/

道歉为我的代码的CoffeeScriptness。这真的很值得学习,特别是因为你可以从Spine来源学到很多东西。

+0

感谢您的帮助@SpoBo ...虽然我可以通过使用标志来解决它,如果设置了标志,只是从事件返回,这有助于我更好地理解MVC如何使用(我是新的到MVC)......但目前还不完全清楚,而且我认为我只需要让它沉入... – uglymunky 2012-02-15 21:34:56

+0

我也可以很好地解释它:pAlex Mccaw的关于javascript应用程序的书可能会帮助你。 http://shop.oreilly.com/product/0636920018421.do – SpoBo 2012-02-15 21:50:55

+0

最好的建议是挖掘并试图理解你所看到的一切。不要盲目信任脚手架代码(实际上,根本不要使用它)。了解所有事情,并问为什么以及如何做。我也涉足骨干,恕我直言,脊柱更容易理解。 – SpoBo 2012-02-15 21:59:33