Backbone.js和jQueryMobile路由没有黑客或其他路由器
我正在使用backbone.js(0.5.3)和JQueryMobile(1.0 beta 2)。 我知道在一起使用这些库时存在路由冲突,我想知道是否有使用它们的解决方案:
- 没有像Ben Nolan的花盆那样侵入jquery移动源代码: http : //bennolan.com/2010/11/23/backbone-and-jquery-mobile.html
- 并且不使用像jquerymobile-router这样的其他路由器(除非没有其他选项…)
我的问题与本文中描述的问题非常相似: jquery-mobile backbone.js routing
当我发出请求时,在新的jquery页面完全加载之前,会触发相应骨干视图的主干render
代码。 我正在尝试在$(".ui-page-active")
DOM元素中呈现我生成的html代码,以定位由jQueryMobile(或“激活”的页面)生成的页面:
MyView = Backbone.View.extend({ el: $(".ui-page-active") render: function(){ console.log(el) } });
但是调用render方法时el
属性为空,因为jquery mobile还没有渲染dom …
谢谢你的帮助 !
更新
Addy Osmani似乎有我的问题的答案:)但它将是他的(伟大的)教程的下一部分: http : //msdn.microsoft.com/en-us/scriptjunkie/hh377172.aspx
好的解决方案是禁用jQuery Mobile ajax加载function并手动调用$.mobile.changePage
方法。
HTML页面:
然后每当触发新路由时,我首先在Backbone View构造函数中构建我的新“jQuery页面canvas”,将其附加到HTML文档body
并将我的el
视图元素设置为这个新div
:
Backbone.View
$("body").prepend(""" """) this.el = $("#logs-view")
并在render
方法中:
// Build the content using undescore.js templating system this.el.find('.cloudy-content').html(this.template({logs : this.collection})); this.find('.cloudy-header').html(this.template_header({logbook: this.logbook})); // Change the page using jquery mobile and reapply jquery styles $.mobile.changePage(this.el, "slide", false, false); this.trigger( "pagecreate" );
像一个魅力,没有任何不必要的黑客:)
这是我完整的Backbone View,如果它可以帮助任何人:
class LogsView extends Backbone.View constructor: (options) -> super $("body").prepend(""" """) @el = $("#logs-view") @logbook = options.logbook @collection.bind 'reset', @render @template = _.template(''' <% logs.each(function(log){ %> - <%= log.getLabel() %>
<% }); %>
''') @template_header = _.template(''' Carnets <%= logbook.get('name') %>
''') render: => # Build the content using undescore.js templating system @el.find('.cloudy-content').html(@template({logs : @collection})) @el.find('.cloudy-header').html(@template_header({logbook: @logbook})) # Change the page using jquery mobile and reapply jquery styles $.mobile.changePage(@el, "slide", false, false) @el.trigger( "pagecreate" )
这可能有点过分,因为我无法测试它,但尝试扩展Backbone的历史记录,让它在实际解雇代码之前监听创建事件。 所以..
MyHistory = Backbone.History.extend({ loadUrl : function(fragmentOverride) { var fragment = this.fragment = this.getFragment(fragmentOverride); var matched = _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { //This is the only change from core code.. //We're just wrapping it into a callback. $('.ui-page-active').one('pagecreate', function () { handler.callback(fragment); }); return true; } }); return matched; } }); MyHistory.start();
这可能会做到,或者至少让你走上我希望的正确道路。
使用jquery 1.2.0,禁用ajax和linkBinding
$(document).bind("mobileinit", function(){ $.mobile.ajaxEnabled = false; $.mobile.hashListeningEnabled = false; $.mobile.linkBindingEnabled = false; $.mobile.pushStateEnabled = false; });
之后,使用正常的Backbone路由,您可以链接#id
Report