重新初始化Meteor中的代码

时间:2015-03-25 02:05:33

标签: javascript jquery meteor

我今天开始为电子商务网站编写一个Meteor应用程序。这是我basic.js文件中的一些代码。

Router.route("/shop", function () {

  this.layout("shop");
  this.render("catalog");

});

呈现/shop时,会执行shop.js内的一些代码:

Template.shop.rendered = function () {
  if ($("figure").hasClass("selected")) {
    var
      productSelected = $("figure.selected"),
      productPrice = productSelected.data("price"),
      productTitle = productSelected.data("product"),
      productLocation = productSelected.find("a").attr("href");

    $(".product-title").html(productTitle);
    $(".product-cost").html(productPrice);
    $(".content__info__title--overview").find("a").attr("href", productLocation);
  }

  // Slideshow
  var galleryItems = $(".content").children("section");

  galleryItems.each(function () {
    var container = $(this);

    // Update slider when user clicks on the preview images
    container.on("click", ".move-down, .move-up", function (event) {
      event.preventDefault();

      if ($(this).hasClass("move-down")) {
        nextSlide(container);
      } else {
        prevSlide(container);
      }

      if ($(this).hasClass("selected")) {
        var
          productPrice = $(this).data("price"),
          productTitle = $(this).data("product");

        $(".product-title").html(productTitle);
        $(".product-cost").html(productPrice);
      }
    });
  });

  // Next Slide
  function nextSlide(container, n) {
    var visibleSlide = container.find("figure.selected");

    if (typeof n === "undefined") {
      n = visibleSlide.index() + 1;
    }

    $("figure.selected").removeClass("selected");

    $(".content__products figure").eq(n).addClass("selected").removeClass("move-down").prevAll().removeClass("move-down move-up").addClass("hide-up").end().prev().removeClass("hide-up").addClass("move-up").end().next().addClass("move-down");
  }

  // Previous Slide
  function prevSlide(container, n) {
    var visibleSlide = container.find("figure.selected");

    if (typeof n === "undefined") {
      n = visibleSlide.index() - 1;
    }

    $("figure.selected").removeClass("selected");

    $(".content__products figure").eq(n).addClass("selected").removeClass("move-up hide-up").nextAll().removeClass("hide-up move-down move-up").end().next().addClass("move-down").end().prev().removeClass("hide-up").addClass("move-up");
  }

});

现在,当应用程序加载时,此功能完全正常,但当我访问其他路径并返回时,shop.js中的所有代码都无效。我不确定我做错了什么,但我喜欢一些指示。

2 个答案:

答案 0 :(得分:3)

更改从此

呈现的模板

Template.shop.rendered  到

Template.catalog.rendered

由于您要呈现catalog route而不是layout template

顺便说一下,我问的是meteor版本,因为在新的1.0.4 meteor版本Template.shop.rendered = function () {}被弃用了,现在我们使用Template.tabletsList.onRendered(function() {});,尝试运行meteor update。

答案 1 :(得分:0)

Ethaan在评论中回答了我的问题。我只需将Template.shop.rendered更改为Template.catalog.rendered。好悲伤!