Search code examples
javascriptjquerybackbone.js

dynamic load template in backbone and comunication between object


i faced ploblem solving write repitation code but i don't want that.
so i think how to solve this problem as beautiful programing aspect.

i thought some solution.
1. parent object add event bind to router
for example, user when visit example.com/#aaa , example.com/#bbb i load router hashtag than handle that event.
if user visit #aaa then load template aaa.

but i find many reference but i don't know how to implement that solution which is parent and child object communication at backbone.js

2. parent object add function
i thought solution that visiting url stored target in router
for example, if i visit example.com/#aaa then router is written target = aaa then parent object loads function and render ansync ajax load template and toss result child object.

but likewise i haven't ablity implement that is.

who will give hint to me?

many backbone.js reference is poorly and difficulty.

router.js (my source)

    var app = app || {};
(function() {
    'use strict';
    var views = app.view = app.view || {};

    app.Router = Backbone.Router.extend({
        initialize: function(){
          this.bind("all", this.change)
          console.log(this.change);
        },
        routes: {
            'situation': 'situationRoute',
            'video': 'videoRoute',
            'culture': 'cultureRoute',
            //와일드카드 디폴트 라우터는 맨 마지막에 삽입.
            '*home': 'homeRoute'
        },
        _bindRoutes: function() {
          if (!this.routes) return;
          this.routes = _.result(this, 'routes');
          var route, routes = _.keys(this.routes);
          while ((route = routes.pop()) != null) {
            this.route(route, this.routes[route]);
          }
        },
        initialize: function() {
            // create the layout once here
            this.layout = new views.Application({
                el: 'body',
            });
        },
        homeRoute: function() {
            var view = new views.Home();
            var target = 'Home';
            this.layout.renderSubpage(target);
            this.layout.setContent(view);
        },
        situationRoute: function() {
            var view = new views.Situation();
            var target = 'Situation';
            this.layout.setContent(view);
        },
        videoRoute: function() {
            var view = new views.Video();
            var target = 'Video';
            this.layout.setContent(view);
        },
        cultureRoute: function(){
            var view = new views.Culture();
            var target = 'Culture';
            this.layout.setContent(view);
        }
      });
      var router = new app.Router();
      Backbone.history.start();
})();

view.js (my source)

var app = app || {};
(function() {
    'use strict';
    //views linitalize
    var views = app.view = app.view || {};
    views.Application = Backbone.View.extend({
        initialize: function() {
           this.$content = this.$('#container');
            //this.$loading = this.$('#loading');
        },
        setContent: function(view, target) {
            var content = this.content;
            this.renderSubpage();
            if (content) content.remove();
            content = this.content = view;
            this.$content.html(content.render().el);
        },
        showSpinner: function() {
          this.$loading.show();
        },
        hideSpinner: function() {
          this.$loading.hide();
        },
        renderSubpage: function(target){
          var target = target;
          var templateName = target;
          var tmpl_dir = '../assets/static';
          var tmpl_url = tmpl_dir + '/' + templateName + '.html';
          var tmpl_string = '';

          $.ajax({
              url: tmpl_url,
              method: 'GET',
              async: false,
              dataType : html,
              success: function (data) {
                  tmpl_string = data;
              }
          });

          var template = _.template(tmpl_string);
          this.$el.html(template);

          return this;
        }
    });
    views.Home = Backbone.View.extend({
      render: function(html) {
        return this;
        //how to get return result? in parent object?
      }
    });
    views.Stuation = Backbone.View.extend({
      render: function() {
       var template = _.template("<strong><% print('Hello ' + page); %></strong>");
       var pageTxt = {page: "About"};
       var html = template(pageTxt);
       this.$el.html(html);
       return this;
      }
    });
    views.Video = Backbone.View.extend({
      render: function() {
       var template = _.template("<strong><% print('Hello ' + page); %></strong>");
       var pageTxt = {page: "Contact"};
       var html = template(pageTxt);
       this.$el.html(html);
       return this;
      }
    });
    views.Culture = Backbone.View.extend({
      render: function() {
       var template = _.template("<strong><% print('Hello ' + page); %></strong>");
       var pageTxt = {page: "Contact"};
       var html = template(pageTxt);
       this.$el.html(html);
       return this;
      }
    });
})();

renderSubpage: function(target) is originally under source.

  views.Home = Backbone.View.extend({
      render: function(html) {
        var templateName = home;
        var tmpl_dir = '../assets/static';
        var tmpl_url = tmpl_dir + '/' + templateName + '.html';
        var tmpl_string = '';

        $.ajax({
            url: tmpl_url,
            method: 'GET',
            async: false,
            dataType : html,
            success: function (data) {
                tmpl_string = data;
            }
        });

        var template = _.template(tmpl_string);
        this.$el.html(template);

        return this;
      }
    });

i don't want repitation code. views.Home = templateName = 'home'; ~~
views.Situation = tamplateName = 'Situation'; ~~

How to fix it?


Solution

  • var app = app || {};
    (function() {
        'use strict';
        //views linitalize
        var views = app.view = app.view || {};
        views.Application = Backbone.View.extend({
            initialize: function() {
               this.$content = this.$('#container');
                //this.$loading = this.$('#loading');
            },
            setContent: function(view, target) {
                var content = this.content;
                var subUrl = this.target;
    
                if (content) content.remove();
                //if (content || target) content.remove()target.remove();
    
                content = this.content = view;
                subUrl = this.target = target;
    
                var templateName = subUrl;
                var tmpl_dir = '../assets/static';
                var tmpl_url = tmpl_dir + '/' + templateName + '.html';
                var tmpl_string = '';
    
                $.ajax({
                    url: tmpl_url,
                    method: 'GET',
                    async: false,
                    dataType : 'html',
                    success: function (data) {
                        tmpl_string = data;
                    }
                });
                console.log(tmpl_string);
                this.$content.html(content.render(tmpl_string).el);
            },
            showSpinner: function() {
              this.$loading.show();
            },
            hideSpinner: function() {
              this.$loading.hide();
            }
        });
        views.Home = Backbone.View.extend({
          render: function(templateName) {
            var template = _.template(templateName);
            this.$el.html(template);
            return this;
          }
        });
    

    i solve that ploblem use function parameter using ajax call subUrl and toss child object then child object renders this template string.