简体   繁体   English

正确使用骨干路由器的方法?

[英]Proper way to use backbone router?

I have the current working code snippet in my backbone router... 我的骨干路由器中有当前的工作代码段...

var currentView;
var DishRoutes = Backbone.Router.extend({
  routes: {
   'dishes': 'allDishes',
   'dishes/': 'allDishes',
  },

  //Show all current dishes on path /dishes 
  allDishes: function () {
   $("#add_a_menu_link").show();
   if (currentView !== undefined) {
    currentView.remove();
   }
   $("#contentArea").empty();
   $("#contentArea").append("<div id=contents></div>");
   dishes.fetch({
    success: function () {
     console.log(dishes);
     currentView = new AllDishesView({
      collection: dishes
      //passes an x so that it will show all the views not just that specific's menus dish...
     }).render("x");
    },
    error: function () {
     console.log("couldn't find dishes:(");
    }
   });
  },

etc... There are many other routes that each have similar things going on for the backbone router. 等等...对于骨干路由器,还有许多其他路由,每个路由都有相似的内容。

var AllDishesView = Backbone.View.extend({
 el: "div#contents",

 initialize: function () {
  console.log(this);
  this.$el.append(this.nDish);
  this.listenTo(this.collection, "add change remove", this.render);
 },

 nDish: $("<ul id='dishlist'></ul>"),
 template: _.template($('#dishTemplate').html()),
 //Render function renders either all or within a passed in parameter...
 render: function (anID) {
  console.log(this);
  var temp = this.template;
  var newDL = this.nDish;
  newDL.empty();
  console.log(anID);
  this.$el.append($('<a href="/dishes/new"></a>'));
  dishes.forEach(function (sDish) {
   //Was this rendering passed with an id?
   var zDish = sDish.toJSON();
   if (anID === "x") {
    console.log(zDish.menu_id);
    newDL.append(temp({
     dish: zDish
    }));
    //If so show only dishes belonging to that Menu!
   } else {
    $("#contents").append($('<a id="add_a_dish_link" href="/#menus/'+anID+'/dishes/add">+ Dish</a>'));
    if (parseInt(zDish.menu_id,10) === parseInt(anID,10)) {
     newDL.append(temp({
      dish: zDish
     }));
    } else {
     console.log("NOT A MATCH!");
    }
   }
  });
  return this;
 }
});

Here is the relevant HTML portion... 这是相关的HTML部分...

<div id="contentArea">

 </div>
<script type="text/template" id="dishTemplate">
  <li>
   <a href="/#dishes/<%= dish.id %>/">
    <%- dish.name %>
   </a>
  </li>
 </script>

While this approach works in that it 100% clears whatever is in my contentArea then adds a new div contents which will contain whatever I want... I like it because it is full proof and reusable... I dislike it because it seems inefficient. 虽然这种方法的工作原理是100%清除了contentArea中的内容,然后添加了一个新的div内容,其中包含了我想要的任何内容...我喜欢它,因为它是充分的证明和可重用的...我不喜欢它,因为它看起来效率很低。 I have heard recently that I should attempt to use to .detach from jQuery and then find a way to reattach it when I'd like that view to show up but I'm not sure how to do that without major scope issues... 最近我听说我应该尝试使用.detach.detach分离,然后在我希望显示该视图时找到一种重新附加它的方法,但是我不确定在没有主要范围问题的情况下该怎么做...

Or if somebody knows the best practice for how to implement easily: Clear this contentArea... put in this new content have it show up on the router. 或者,如果有人知道如何轻松实现的最佳实践:清除此contentArea ...放在此新内容中,使其显示在路由器上。 With the most efficient strategy which requires the least amount of DOM re-rendering and if possible no additional fetch if I were to come back to the allDishes. 使用最有效的策略,它需要最少的DOM重新渲染量,并且如果可能的话,如果我要返回allDishes,则无需额外提取。 Thank you! 谢谢!

Use App router only to route your application, All the data fetching has to be done in the View to keep code clean. 仅使用App router路由您的应用程序,必须在View中完成所有数据提取以保持代码干净。

Just create a DishView in Your router.Don't add any logic to it, keep clean. 只需在路由器中创建一个DishView,不要添加任何逻辑,请保持清洁。

 allDishes: function () {
  // Your Dom operations here
  currentView = new AllDishesView({});
  // Now just create a View and attach to DOM.

  },

Now fetch your collection in your View 现在在视图中获取您的收藏

var AllDishesView = Backbone.View.extend({
 el: "div#contents",

     initialize: function () {
      this.$el.append(this.nDish);
      this.collection = new DishCollection();
      this.listenTo(this.collection, "add change remove sync", this.render);
      //render on collection on sync also
     },

Now the logic in approuter is minimised. 现在最小化了approuter中的逻辑。
If you dont want to fect the collection every time just check for the instance of your view ,if exists just add it to the DOM. 如果您不想每次都影响集合,只需检查视图实例,如果存在,只需将其添加到DOM中。 like(In router) 喜欢(在路由器中)

 allDishes: function () {
  // Your Dom operations here
  if(.isUndefined(this.currentView){ 
    this.currentView = new AllDishesView({});
  }else{
      // Just add it back to the DOM
        $("#contentArea").append(this.currentView.el)   
  }
  // Now just create a View and attach to DOM.

  },

There are many best practices and optimizations that can be added here but that will be a big list. 可以在此处添加许多最佳实践和优化,但这将是一个很大的清单。

Note: Use deleagteEvents if you are appending view to DOM, else the view's event wont work. 注意:如果要将视图追加到DOM,请使用deleagteEvents,否则视图的事件将无法工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM