grails,backbone.js,handlebars , passing backbone collection to view


passing backbone collection to view

Question:

Tag: grails,backbone.js,handlebars

I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work.

I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will do an ajax call to the backend for updated pricing data. I do not want to expose my pricing algorithm to the front end, so I was thinking I would use backbone to handle my ajax request / template.

I do not want to fully rely on js to create my UI, so on the initial page load, I'll build the gsp view with grails. Only problem I've noticed was my gsp view was being replaced by my handlebars template on initial page load. I guess this is fine, except it does two identical queries which isn't optimal.

Anyhow my code that does not seem to be working.

<script id="priceTemplate" type="text/x-handlebars-template">
    <tr>
        <td><input type="radio" value="" name="quantity">{{quantity}}</td>
         <td class="price"><span>{{price}}</span></td>
        <td class="discount"><span>{{discount}}</span></td>
    </tr>
</script>

<asset:javascript src="bb_product/config.js"/>

<script>   
    var prices = new models.PriceList([],{productId:${productInstance.id}});
    var priceView = new PriceView({collection: prices});
    prices.fetch();     
</script>

Models

var models = {};

models.PriceModel = Backbone.Model.extend({   
    //Is the model automatically populated from the collections json response?
})

models.PriceList = Backbone.Collection.extend({
    initialize: function(models, options) {     
        this.productId = options.productId;
    },
    model: models.PriceModel,
    url: function() {
           return '../product/pricing/' + this.productId + '.json'
        }  
});

View

var PriceView = Backbone.View.extend({
    el: '#product-quantities',

    template: Handlebars.compile($("#priceTemplate").html()),

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

   render: function() {
       console.log('collection ' + this.collection.toJSON()) //comes back empty
       this.$el.html( this.template(this.collection.toJSON()));
   }

});

json returned from url

[{"id":1,"quantity":10,"price":"10","discount":"10"},{"id":2,"quantity":50,"price":"20","discount"
:"10"}]

To initially get this up and working, what am I missing to display all items in the json object?

I've also see this code around, not sure what it does this.listenTo(this.collection, 'reset', this.render);


Answer:

The reason you don't see any items is that the items aren't actually in the collection until after the view is rendered. Look at these two lines of code:

var priceView = new PriceView({collection: prices});
prices.fetch();

The first line renders the view (since you're calling render from within initialize). However, at that time, the prices collection is empty. Then, the second line fetches the data from the server and loads it into the collection; but by that time, the view has been rendered.

That last line of code you posted is the key to fixing this:

this.listenTo(this.collection, 'reset', this.render);

Usually, you'll put this inside the initialize function in your view class. What this does is "listen" to the collection instance, and when the reset event occurs, it will call the this.render function. (Of course, the method this.listenTo can "listen" to other objects for other events; see more details in the Backbone documentation).

If you add that line to the view's initialize function, the view will re-render whenever a "reset" event happens on the collection.

HOWEVER, by default, the "reset" event happens when all the models in the collection are replaced with another set of models, and this doesn't happen by default when you call a collection's fetch method (instead, the collection will try to "smart-update"). To force a reset of the collection when using fetch, pass {reset: true} as a parameter:

prices.fetch({reset: true});

Related:


Why `init` of shim in my require.js configuration not called?


javascript,django,backbone.js,requirejs,csrf
Update: I was writing a small module to handle this csrf token problem in backbone until I got push notification of @Louis's answer. His answer is quite elegant and seems nice, but I'll leave a link to my backbone.csrf module github repo just for anyone who needs it. ==================================================================== I'm...

Backbone's success callback called before jquery's ajaxSuccess


jquery,ajax,backbone.js,callback
I would like to make sure that jQuery's ajaxSuccess callback is called before Backbone's success, which is not the case in my experience. I would like this someModel.fetch({ success: function() { console.log('2'); } }); $(document).ajaxSuccess(function(event, xhr, ajaxOptions) { console.log('1'); }); to log 1, 2 and not 2, 1. The reason...

grails 3.0.1 scaffolded view does not show domain relationship


grails,scaffolding
I am following the example in the book "Grails a Quick-Start Guide" using Grails 3.0.1 with following domains package com.tekdays class TekEvent { static constraints = { name() city() description maxSize:5000 organizer() venue() startDate() endDate() } String city String name TekUser organizer String venue Date startDate Date endDate String description...

Backbone this.el is undefined


jquery,backbone.js
I've been following along to the a tutorial i found on youtube. https://www.youtube.com/watch?v=vPW1inIsln4 In the tutorial I don't see him defining el : ... but he's calling this.$el and it appears to be working. In jsfiddle, I have been following along, but get a js error saying Backone this.el is...

Use data-* attribute in grails g.link generated in tagLib


grails
Is there a way to use data- attributes in g.link generated by a tagLib? I want to store some DOM info instead of using params in the g.link which results in query parameters. Example: out << g.link(controller: "calendar", action: "info", params: [id: cal_id], data-info: "abc") { "click me " }...

Handlebars: return hash from helper


javascript,backbone.js,coffeescript,handlebars.js,handlebars
Can i return hash from Handlebars helper? I tried this: In my view: initialize: -> super this.hash = {key1: 'test1', key2: 'test2'} Handlebars.registerHelper 'show', => return this.hash In template: {{show.key1}} What am i doing wrong? Thanks!...

Grails JAX-RS Calling a class in src/groovy giving error - Message: No signature of method: is applicable for argument types


grails,groovy,jax-rs
While developing the rest api using jaxrs plugin I need to create some common class which I have created in "src/groovy". Below is the class class ValidateToken { String validate(String token){ println(token) return "test" } //... In resource file(jaxrs) this is what I am doing def instance=ValidateToken.validate("test") This throws error...

grails one to many with additional column


grails,relationship,one-to-many
In my Grails project I need to have a 1:N relationship between two domain classes. So, I've created the following domain class: class Receipt_HealthService { Receipt receipt HealthService healthService int quantity = 1 static constraints = { } } and in Receipt I have the following: @NotNull static hasMany =...

Decode base64 image in Grails [duplicate]


grails,groovy
This question already has an answer here: Convert base64 string to image 3 answers I have a post api where I am sending a json string which contain the base64 encoded image.Below is the json string { "imageData":"base64encoded string", "status":"1" } where base64encode string is iVBORw0KGgoAAAANSUhEUgAAAHgAAACgCAIAAABIaz/HAAAAAXNSR0IArs4c6QAA\r\nABxpRE9UAAAAAgAAAAAAAABQAAAAKAAAAFAAAABQAABWL3xrAqoAAEAASURBVHgB\r\nlL2Fe1t7mueZme6uewNGMUu2LNkyySSjDJKZmZkSO8zM7CTmmJnZYbxUVbdgsKp7\r\nqqdrdp I cant post...

Backbone datatypes - type casting?


javascript,backbone.js
It just took me over an hour to find out that a Backbone query on a collection was failing because I queried the wrong data type. So this query failed because I used the wrong data type for id: element = collection.findWhere({id: "123", att: true}); This one worked and returned...

How to declare javascript asset in the view to be rendered within the footer using Grails Asset Pipeline


grails,grails-plugin
Since there is no deferred option for: <asset:javascript src="custom_view_script.js"/> What else can be used, outside of resource plugin, to place view specific script right before the closing body tag and without declaring it globally in layout? I do know about: <asset:deferredScripts/> but that only handles on page script and not...

Groovy - timestamp from minutes


oracle,grails,groovy,timestamp
I have an array or times/values coming back to be in an array like: [0, 60] Which are times in minutes, 0 = 12:00 a.m, 60 = 1:00 a.m. I am wanting to store these in an oracle database as timestamps. How do I convert minutes into timestamps in groovy?...

passing backbone collection to view


grails,backbone.js,handlebars
I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work. I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will...

Extend Coffeescript subclass function from parent in marionette


javascript,backbone.js,coffeescript,marionette
I've got a "FormView" class in my Marionette application that sets up a lot of things for form submissions around my app. I use it every time there is a form. I've also got some helpers that I want to pass into every form template via the templateHelpers method, but...

Backbone.js remove model from collection


javascript,backbone.js,backbone-collections
I'm learning Backbone and for the life of me I can't remove a model from a collection. The collection 'remove' event fires, but the collection appears to remain the same. Here's what I have so far: http://jsbin.com/becamo/edit?js,output I remove the model from the collection upon click. Then, the list view...

Backbone.js - Model's attribute is not getting passed to view correctly


backbone.js
I am very new to backbone and trying to understand why "title" is not getting passed to view and printing correctly. If I create model with title properties it passes to view and prints fine. Any pointer will be greatly appreciated. HTML: $(document).ready(function(){ //Model var Appointment = Backbone.Model.extend({ urlRoot :...

Backbone render template in side el's nested id


javascript,jquery,backbone.js
I have my html setup like this. <div id="product-module"> <ul id="product"> <li><input name="product" type="radio"/></li> <li><input name="product" type="radio"/></li> <li><input name="product" type="radio"/></li> </ul> <table id="quantities"/> <script id="myTemplate" type="text/x-handlebars-template"> {{#each this}} <tr> <td class="quantity"> <label class="checked" for="quantity_{{id}}"> <input type="radio" value=""...

Grails logging auto inject


grails,logback
I use grails 3.0.2 and logback. How can I use this logger in my code, can I somehow autoinject it, like log.debug() in grails 2.x which was using org.apache.commons.logging.Log?

Add two events in backbone.js


javascript,jquery,backbone.js
I added two jQuery events, the second jQuery event is not triggering. What might be the issue? Here is my code : var ListView = Backbone.View.extend({ events: function() { $('#couponcheck2').click(function(e) { e.preventDefault(); $('#couponcheck').empty(); $('#couponcheck').append('<div class="col-xs-8"><input type="text" class="form-control" id="enterCoupon"></div>'); $('#couponcheck').append('<div class="col-xs-8"><button type="button" class="btn btn-success btn-sm" id="couponbutton"><span...

unable to resolve class org.apache.commons.net.ftp in grails


grails,apache-commons
I am developing a module in which some file need to be uploaded on a ftp server for that I have added the "commons-net-3.3.jar" in my grails app & while using it import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPClientConfig import org.apache.commons.net.ftp.FTPFile import org.apache.commons.net.ftp.FTPReply It is throwing the error unable to resolve...

CollectionView - collection data not being passed to childView


javascript,backbone.js,marionette
I'm trying to make the collectionView work , but I'm not really sure whether the CollectionView initiates the fetch method automatically and then populates the ChildViews with the fetched data. Or is it something I need to do manually? I have checked the Marionette doc page but I couldn't find...

Merge two object arrays for Chart


javascript,arrays,backbone.js,lodash
I've two arrays which I'm going to merge and then load in chart. range = date array generated from moment.js, there is date of every day in example one month or specific date range with one another attribute count: "0" data = fetched data from database through backbone Now I...

Grails 3.0 Searchable plugin


maven,grails
I've tried to use the searchable plugin in grails 3.0, but I am not sure wheather it is compatible or not. I've added compile "org.grails.plugins:searchable" to the dependencies. The build completes but yields a NotSearializableException: > Configuring > 1/1 projects > Resolving dependencies ':agent' > Resolving dependencies ': BUILD SUCCESSFUL...

Underscore templates with Backbone


javascript,backbone.js,underscore.js,underscore.js-templating
I'm completely new in backbone framework. I have a model itemsOnSaleModel that contains an array of items and a View itemListView that render these items. The problem is that I can't figure out how to write the template correctly. Usually in this case I would have written something like this:...

Error when using angular with Grails


angularjs,grails
Here is my index.gsp <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src="/js/angular.min.js"></script> </html> When I build an app, There is an error like this, Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=myApp&p1=Error%3A%…20at%20d%20(http%3A%2F%2Flocalhost%3A8000%2Fjs%2Fangular.min.js%3A17%3A381)...

File upload with grails and jquery


jquery,grails
I have a form with multiple inputs plus a doc or pdf file upload. //Multiple input fields are here then upload -> <div class="controls"> <div class="fileupload ${ person?.attachment ? 'fileupload-exists' : 'fileupload-new' }" id="attachment" data-provides="fileupload" data-name="attachment"> <span class="btn btn-file"> <span class="fileupload-new">Add</span> <span class="fileupload-exists">Change</span> <input type="file" /> </span> <span class="fileupload-preview"></span>...

[B cannot be cast to java.sql.Blob


grails,gorm
This is my domain class class TimesheetSubmission { Date submissionDate=new Date() String foreman String shift String jobId Date date byte[] xmlSubmission String xmlResponse static constraints = { submissionDate nullable: false foreman nullable: false shift nullable: false jobId nullable: false date nullable: false xmlSubmission nullable: true xmlResponse nullable: false } static...

Grails 3.0.2 missing generate-views


java,grails,command-line,ide,ggts
I'm new to grails and I'm trying to get my first HelloWorld from it. I can generate it with the controller, but I can't create a view because it isn't listed in the Grails (3.0.2) list of command. Because any IDE support grails 3.*, I can't create it by that...

CSS Selector Equivalent Of jQuery.find in backbone.js?


javascript,jquery,backbone.js,selector
I have a Marionette view that has the following code: onRender: { $('#someDiv').find('a').click(function(){ // some code here }); } But I want to refactor to something like this: events: { 'click [selector here]': 'executeCode' }, executeCode: function() { // some code here } Is this possible?...

Grails: Do addTo* and removeFrom* require a call to save?


grails,gorm,grails-2.0,grails-domain-class
In the docs some examples have a call to save whereas some others do not. I'm assuming that addTo* needs the call to save whereas removeFrom* doesn't. Am I mistaken?

Comparison Express JS, Angular JS vs Backbone JS [closed]


angularjs,backbone.js,express,requirements
I am starting to learn node js for a while and it seem amazing. When I start to apply nodejs to build a scalable website, I am wondering to do Express for back-end, BackBone Js or Angular JS for front-end, people said Express JS is very fast, while Backbone.js seem...

Where to format collections / objects


javascript,backbone.js,architecture,project-structure
From front end architectural point of view, what is the most common way to store scripts that perform transformations on collections of objects/models? In what folder would you store it, and what would you name the file / function? Currently I have models, views, controllers, repositories, presenters, components and services....

Persisting data client side for event driven approach


javascript,backbone.js
I have an application that renders activities and looks like this: The map should render markers based on some criteria (date_start, date_end, map_bounds). Activities are loaded from a REST api with ajax. The front end approach is event driven (using Backbone / Marionette); activities are dynamically udpated when the date...

What is the use of HTML5 pushState in Backbone History Start method


javascript,html5,backbone.js
I have a simple Backbone app. I am trying to understand the difference created by passing pusState: true when starting Backbone.History object. JavaScript var r = new (Backbone.Router.extend({ routes: { "users": "allUsers", "users/new": "createUser" }, allUsers: function () { v.render("showing all users"); }, createUser: function () { v.render("showing form for...

Marionette CompositeView - change in template each nth items


twitter-bootstrap,backbone.js,marionette,composite-view
I'm using Marionette for a while, but I'm not sure how I can do what I want, in a simple manner. I have a composite view, which renders something like this: <div class="row"> <div class="col-xs-12"> <div id="items"></div> </div> </div> Each of my item is being rendered as a: <div class="col-xs-3">foo</div>...

Intercepting login calls with Spring-Security-Rest plugin in Grails


rest,grails,spring-security
I am using the spring security rest plugin for Grails to provide a login mechanism for an AngularJS app. Login works fine, but I can't figure out how to intercept login calls, in order to store additional statistics on (invalid/valid) login attempts. As I am quite new to Spring Security...

Grails 2.4.4 spring security role doesn't apply to user


java,spring,grails,spring-security,spring-annotations
I have controller: class AdminController { def springSecurityService @Secured(['ROLE_ADMIN', 'ROLE_USER']) def index() { render "test"; } And user with role ROLE_ADMIN in the table: But, when I use: springSecurityService.getPrincipal().getAuthorities() There is only one role: ROLE_NO_ROLES Why? def loggedInUser = springSecurityService.currentUser; returns correct user. Config: ... grails.plugin.springsecurity.userLookup.userDomainClassName = '...' grails.plugin.springsecurity.userLookup.authorityJoinClassName =...

alert grails pagination current offset value


grails,pagination
I am using Grails 2.4.2. I have a list which is using pagination. When I mouse hover a number or next page icon it shows current offset number as tool tip. Can I alert this offset number or get my list's current page offset number?

What is the correct way to override Marionette compositeview render


backbone.js,marionette
I am showing a table view using Marionette's composite view. The composite view's template has a tbody with an initial which shows a loadding animation gif. Now, when the render method is called, I want to remove this initial row and then append the results of collection fetch. However the...

Marionette - listenTo a custom event triggered from a collection


javascript,backbone.js,marionette
I'm using a Event Aggregator(EA) to keep track of all events in my app. But there is one situation I could not make the EA listen to a custom event triggered from a collection. See more details below. eMgr (Event Manager i.e Event aggregator): define(['backbone.wreqr'],function(Wreqr){ "use strict"; return new Wreqr.EventAggregator();...

Can't call fetch directly in Backbone model listenTo


javascript,backbone.js,coffeescript
I'm trying to have a model listen to a collection and fetch itself when the collection changes: class Team extends Backbone.Model urlRoot: '/team', initialize: function(attributes, options) { this.listenTo(members, 'change', this.fetch) The fetch does seem to trigger, but the url is all messed up, and to get it to work I...

Grails: Carry forward params on g:actionSubmit is clicked


grails,gsp
How to carry forward the parameters when g:actionSubmit button is clicked? Here is my gsp code: <g:checkBox name="msgCheck" checked="" value="${userInstance.emailId}"></g:checkBox> ... <g:actionSubmit class="update" action="delete" value="Delete" params="${params}"></g:actionSubmit> Here is my controller code: def delete() { try { def user_list = params.msgCheck //deleting the user //successful. redirect(action: "list", params: params) } catch...

Render a controller into a String


grails,grails-2.0
I can render a template or a view into a String, but how can I render a controller into a String ? I would like to perform this kind of operation: def myAction = { ... def html = renderToString(controller: 'myController', action: 'myAction', params: [what:'ever']) render modify(html) ... } ...

Log Grails Pre 3.0 startup time


grails
In Grails 2.x.x is it somehow possible to log the startup time? We are currently trying to optimize the application startup and having the startup time logged would help tremendously.

grails DataSource.groovy refer bean for decoding password


grails
Referring https://jira.grails.org/browse/GRAILS-3620, we need to specify a class with static methods to decode the encrypted password in DataSource config. For passwordEncryptionCodec property, is it possible to refer to a bean defined in resources.xml or any other grails bean definition files? For ex: having a decrypted Properties bean in resoures.xml or...

Dropzone.js status is pending and not uploading a file


javascript,node.js,backbone.js,express,dropzone.js
I am using Multer in back-end to handle file upload and Dropzone.js in front-end. Everything is fine when I use Postman to test my back-end code, but in when I use Dropzone the status is pending and file not getting uploaded. Then after 4 minutes of waiting I get Timeout...

Grails 2.3.9 - Error: ClassNotFoundException: grails.plugin.spock.test.GrailsSpecTestType


grails,grails-plugin,spock,grails-2.3
Whenever I enter the grails command: test-app I get this error: Error executing script TestApp: java.lang.ClassNotFoundException: grails.plugin.spock.test.GrailsSpecTestType (Use --stacktrace to see the full trace) In my BuildConfig.groovy I have: grails.project.dependency.resolution = { ... plugins { ... test ":spock:0.7" } } I've tried replacing it with compile ":spock:0.7" . I've also...

backbone stickit - reverting model changes


javascript,backbone.js,2-way-object-databinding
I'm now testing backbone stickit for two-way data binding. Is there a way to revert the changes, for example, while editing a model data through a form, the user press the cancel button, as in the pic below It seems the model was changed on the fly as we type...

Encryption of strings using AES 128 in Java/grails


java,grails,encryption,aes
I would like to encrypt 3 strings using AES 128 in Java / Grails, and using the code below, but i get the error "An error occurred when encrypting", can someone tell me what is wrong with my code, how to fix it. thanks in advance and to Stackoverflow. String...