Javascript Backbone.js - 在视图上的“单击”事件之后导航到路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7511567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:33:21  来源:igfitidea点击:

Backbone.js - navigating to a route after the "click" event on a view

javascriptbackbone.js

提问by ericbae

My "view" is set up as below. simple.

我的“视图”设置如下。简单的。

var ItemView = Backbone.View.extend({
  tagName : "li",

  events : {
    "click" : "display"
  },

  display : function() {
    //app.navigate('item'); // take me to my route!
  }
});

And I have my router

我有我的路由器

var App = Backbone.Router.extend({

  routes: {
    "" : "index",
    "item" : "view_item"
  },

  index: function() {
    alert('hi!');
  },

  view_item: function() {
    alert('bye!');
  }
});

app = new App();
Backbone.history.start();

Now, when I click on ItemView, it should run "display" method and I want the display method to take me to the route I specified in routes "item".

现在,当我单击 ItemView 时,它应该运行“display”方法,并且我希望 display 方法将我带到我在“item”路线中指定的路线。

Is this possible? I thought "navigate" function will work, but it doesn't. How could I achieve this?

这可能吗?我认为“导航”功能会起作用,但它不会。我怎么能做到这一点?

回答by Skylar Anderson

 display : function() {
    app.navigate('item', true);
  }

You need the second parameter set to true.

您需要将第二个参数设置为 true。

From the Backbone documentation:

从主干文档:

navigaterouter.navigate(fragment, [triggerRoute]) Whenever you reach a point in your application that you'd like to save as a URL, call navigate in order to update the URL. If you wish to also call the route function, pass triggerRoute.

navigaterouter.navigate(fragment, [triggerRoute]) 每当您到达应用程序中想要保存为 URL 的点时,请调用 navigate 以更新 URL。如果您还希望调用路由函数,请传递 triggerRoute。

回答by rcarvalho

Or you can do it directly from html, if you're using "< a >" tag.

或者,如果您使用“< a >”标签,则可以直接从 html 执行此操作。

example:

例子:

<a href="#item">Show Itens</a>

It also works, I prefer this way when of course is possible.

它也有效,当然在可能的情况下我更喜欢这种方式。