ConfuXigrator
ConfuXigrator

Reputation: 63

How to load external html template in backbone view

I am a novice to backbone and need your help. I am facing an issue where I am not able to load an external template. Here's the question:

I have a home_template.html which has a div i need to populate with an external template

    <div class="ASContainer" id="asContainerView">
    </div>

Now I have a Homeview.js

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'text!templates/home/homeTemplate.html',
    'text!templates/home/activityTemplate.html',
    'text!templates/compose/composeTemplate.html',
    'text!templates/comments/commentsTemplate.html',
    'views/home/ActivityListView',
    'views/ComposePost/ComposePostView',
    'views/ComposePost/WSListView', 
], function ($, _, Backbone, Marionette, homeTemplate, activityTemplate, composeTemplate, commentsTemplate, ActivityListView, ComposePostView, WSListView) {

var HomeView = Backbone.View.extend({
        el : $("#page"),

        transition : 'slide',
        activitiesListView : null,

        initialize : function () {

            this.$el.attr('data-transition', this.transition);
            this.currentUserLogin = currentUserLogin;
            var that = this;
            this.activityId = this.options.activityId;
            this.workspaceUrl = this.options.workspaceUrl;
            this.context = this.options.parentContext;
        },
        events : {
            'click #composePost' : 'onComposePost',
            'click #btnPost' : 'onPostClick',
            'click #cancelpost' : 'onCancelClick',
            'click #comments' : 'OnCommentsClick',
            'click #LeftNavIcon' : 'OnLeftNavigationClick',

        },
        render : function () { debugger
            var that = this;
            $('.menu li').removeClass('active');
            $('.menu li a[href="#"]').parent().addClass('active');

            that.callAjaxReload("homeTemplate.html", "aaa", "AS_Content");

            this.$el.html(homeTemplate);

            $("#userloggedin").text(currentUserLogin);

            //var sidebarView = new SidebarView();
            //sidebarView.render();

        },
         cleanup: function() { 
            this.undelegateEvents();
            $(this.el).empty();
        },

        getActivitiesForWorkspace: function(ActStreamPageSize, activityId) { debugger;
            try {
                //LogInfoStart('getActivitiesStreamAjaxCommand');
                var BrowserTimeZone = getTimezoneName();
                $.ajax({
                    type : "POST",
                    url : siteBaseUrl + '/ActivityStreamClientService.svc/GetActivityStreamForWorkSpace',
                    contentType : "application/json; charset=utf-8",
                    dataType : 'json',
                    cache : false,
                    data : JSON.stringify({
                        workspaceUrl : siteBaseUrl,
                        userLoginName : currentUser,
                        filterValue : "All",
                        searchTxt : '',
                        searchFilter : "All", //add
                        searchTag : '', //add
                        activityId : activityId,
                        pageSize : 5,
                        commentCount : 9999,
                        tabContext : "MY",
                        customFilter : '',
                        activityMode : '',
                        time : new Date(), // need to add this for iPhone caching ajax posts problem!
                        browserTimeZone : BrowserTimeZone, // added for time zone changes in new ux
                        MySiteMode : '',
                        MySiteLogggedInUserName : '',
                        MySiteProfileVisitorruserName : '',
                        MySiteDetails : ''
                    }),
                    processData : true,
                    success : function (msg) { debugger;
                        //Define collection
                        var model = Backbone.Model.extend({});
                        var collection = Backbone.Collection.extend({
                                model : model
                            });
                        //var activityListView = ActivityListView({model : activitiesList});
                        //Add it to the collection after fetch
                        msgActivities = msg.GetActivityStreamForWorkSpaceResult;

                        var activitiesList = new collection(msgActivities);
                        //gtemplate = $('#personTemplate').html();
                        //var template: _.template( $('#personTemplate').html());
                        if (activityId <= 0) {
                            console.log("here");

                            $("#asContainerView").html(ActivityListView({model : activitiesList}).el);

                            }
                        else {
                                console.log("I am there");
                            $(new ActivityListView({model : activitiesList}).el).appendTo("#asContainerView");
                        }
                        lastactivityId = msgActivities[(msgActivities.length - 1)].ActivityID;

                        //Add collection to context
                        // that.context.collections.add(activitiesCollection, collectionTitle);
                        //that.context.currentCollectionNameId = collectionTitle; // for details page to work (ws url of stream is different than the activity ws url!!

                        //that.GetActivitiesSuccess(msg, dfd, that.eventData.onSuccessCallback);
                        //customFilterValue = "all";
                    },
                    error : function (err) {
                        //LogError('activities-ajax-commands.js getActivitiesStreamAjaxCommand.execute - Error', '', //that.context.parentContext.mainGlobalObject.CurrentUser, err);
                        //$.utilsSystem.alert('Error getting activities.', 'single');
                        //if (onSuccessCallback) onSuccessCallback();
                    }

                });
            } catch (err) {
                // LogError('activities-ajax-commands.js getActivitiesStreamAjaxCommand.GetActivitiesError', '', $.SX.mainGlobalObject.CurrentUser, err);
            }
        },
        callAjaxReload: function (url, parameter, classname) { debugger;
            var that = this;
            console.log(classname);
            // $.ajax({
            //url:url,
            //dataType:datatype,
            //success:function(data){

            // }
            //GetConfigurationSettings
            var BrowserTimeZone = getTimezoneName();

            $.ajax({ 
                type : "GET",
                url : siteBaseUrl + '/ActivityStreamClientService.svc/GetConfigurationSettings', //this.ActivitiesStreamOptions.ACTSTREAMGETCONFIGITEMURL,
                contentType : "application/json; charset=utf-8",
                dataType : 'json',
                data : {
                    configurationItem : "ActivityStreamCount",
                    workspaceUrl : siteBaseUrl //this.ActivitiesStreamOptions.ActStreamWorkspaceUrl
                },
                async : false,
                success : function (msg) { debugger;
                    //ActivitiesStreamOptions.ActStreamPageSize = msg.GetConfigurationSettingsResult[0];
                    ActivityStreamPageSize = msg.GetConfigurationSettingsResult[0];
                    that.**getActivitiesForWorkspace**(msg.GetConfigurationSettingsResult[0], 0);
                    debugger;
                    //console.log(ActivitiesStreamOptions.ActStreamPageSize);
                    //  ActivitiesStreamOptions.ActStreamFilterValue = '';
                },
                error : function (err) {
                    console.log("Error: Hasan");
                    //LogError('activities-ajax-commands.js getActivitiesStreamAjaxCommand.execute - Error', '', that.context.parentContext.mainGlobalObject.CurrentUser, err);
                    // that.ActivitiesStreamOptions.ActStreamPageSize = 5;
                }
            });

            //})

            //$('.'+classname).html(data);
        },


    });

return HomeView;

});

Now this HomeView js has two functions. callAjaxReload and getActivitiesForWorkspace. The render calls callAjaxReload which has an ajax function which on success calls getActivitiesForWorkspace.Now getActivitiesForWorkspace also has an ajax function and on whose success I have to pass the model to another View ActivityList View and appends that the template under the div id asContainerView.

The problem which I am facing is that the this line below fails to load the ActivityListView.

$("#asContainerView").html(ActivityListView({model : activitiesList}).el);

I get an error that ActivityListView is undefined.

Can anybody help me here.

The ActivityListView.js is

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'views/home/ActivityListItemView',
    'text!templates/home/activityTemplate.html',
], function ($, _, Backbone, Marionette, ActivityListItemView, activityTemplate) {

var ActivityListView = Backbone.View.extend({

    initialize: function () {
        this.render();
    },

    render: function () { 
        var activities = this.model.models;
        var len = activities.length;
        //var startPos = (this.options.page - 1) * 8;
        //var endPos = Math.min(startPos + 8, len);
        var startPos = 0;
        var endPos = len;

        //$(this.el).html('<ul class="thumbnails"></ul>');

        for (var i = startPos; i < endPos; i++) {
          { //$(this.el).append(new ActivityListItemView({model: activities[i]}).initialize);
                            //console.log("activities[i]:"activityListItemView.model.attributes.ActivityTypeSourceName);
            var activityListItemView = new ActivityListItemView({ model: activities[i] });

            $(this.el).append(activityListItemView.el);
            }
//console.log(activityListItemView.el);
           //var personView = new PersonView({ model: person });
        }

        //$(this.el).append(new Paginator({model: this.model, page: this.options.page}).render().el);

        return this;
    }
});

});

and this calls ActivityListItemView.js

define([
    'jquery',
    'underscore',
    'backbone',
    'marionette',
    'text!templates/home/activityTemplate.html',
], function ($, _, Backbone, Marionette, activityTemplate) {
var ActivityListItemView = Backbone.View.extend({

    tagName: "div",
    template: activityTemplate,
    //my_template: _.template(gtemplate1),
    //my_template: _.template("<p class=\"AS_Content\"> <%= ActivityContent %> </p> "),

     initialize: function(){
      this.render();
    },

     render: function(){ debugger;
      //$(this.el).html(this.template(this.model.toJSON()));

      this.$el.html(_.template(this.template, { user: this.model.attributes }));
        //this.$el( this.template(this.model.toJSON()));    
      //this.$el.html( this.template(this.model.toJSON()));

    }
});

});

Thanks

Upvotes: 2

Views: 1681

Answers (2)

Oleksii
Oleksii

Reputation: 301

Your requirejs definitions should return ActivityListView and ActivityListItemView

The function should return an object that defines the module

see http://www.requirejs.org/docs/api.html#defdep

Upvotes: 1

machineghost
machineghost

Reputation: 35790

You have:

$("#asContainerView").html(ActivityListView({model : activitiesList}).el);

but your syntax is off; when you want to instantiate a new Backbone.View you need to use the new keyword:

$("#asContainerView").html(new ActivityListView({model : activitiesList}).el);

Upvotes: 1

Related Questions