2012-11-20 9 views
2

我知道這不是你應該這樣做的,但我們有一個傳統的jQuery應用程序,並且已經有一些關於將它移動到主幹的討論。一個成語將被吸引的是這樣的:一起使用主幹和jQuery並通過jQuery訪問數據值

<script type="text/html" id="mi_form_template"> 
    the data-item-id is the value we are interested in!!! 
<button id="item" data-item-id='23'>here is item</button> 
    </script> 

我知道,你不應該來存儲這樣的信息與骨幹DOM。但希望能夠預見關於此的討論。

我可以像這樣訪問item-id嗎?

ItemsRouter = Backbone.Router.extend({ 
    routes: { 
     "new": "newProduct", 
     "": "index" 
    }, 
    newProduct: function() { 
     alert('here is newProduct'); 
     var item_id=$(this).data('item-id'); // <- can we do this??? 
     new ItemFormView({model: new Item()}); 
    }, 
    ind ... 

從初步測試,這將無法正常工作 - 它看起來像參考這是行不通的。這是可能的嗎?

提前THX

回答

1

通常你會訪問通過視圖(不是路由器)以這樣的數據屬性:

events: { 
    'click #item': 'newProduct' 
}, 
newProduct: function(ev) { 
    var item_id = $(ev.target).data('item-id'); 
    // And now do whatever makes sense, possibly even trigger 
    // a route that contains `item_id`. 
} 

的路由處理程序不知道是什麼觸發它,它只知道它應該處理特定的URL模式。如果你想用一個路由器這樣的事情,那麼你會希望有一個鏈接:

<a href="/new/23">...</a> 

然後在路由器:

routes: { 
    'new/:item_id': 'newProduct' 
}, 
newProduct: function(item_id) { 
    // Do things with item_id 
} 

所以,你仍然可以使用數據屬性(這是可以用Backbone BTW),但你可能會在視圖的事件處理程序中而不是在路由器中訪問它們。

+0

thx畝,剛剛意識到我的錯誤與路由器,並回去編輯... ev.target和ev.currentTarget之間有任何區別?看起來我們可以用上面提到的成語代替我們的jquery。 thx再次,我真的很感激。 – timpone

+0

@timpone:'target'和'currentTarget'不一樣,'target'或多或少是被點擊的東西,但'currentTarget'是處理委託的東西。這裏有更多的信息(包括一些演示鏈接):http://stackoverflow.com/a/10078740/479863 –