0

Using backbone and requirejs. I want to use an input mask. I put another jQuery construct in the view and it works just fine, but the mask doesn't show up in the phone fields. What am I doing wrong? Thanks.

render: function(){
var compiledTemplate = _.template( RegisterTemplate, this.model );
this.$el.html(compiledTemplate); 

  $("#custphone").mask("(999) 999-9999");  //masks not showing up
  $("#custphone2").mask("(999) 999-9999");
  $("#custzip").mask("99999");
  $("#venuezip").mask("99999");

  $().acknowledgeinput({               //works fine!
          success_color: '#00FF00',
      danger_color: '#FF0000',
      update_on: 'keyup'
   });
Tom
  • 67
  • 1
  • 1
  • 7

1 Answers1

0

The usual pattern for putting a view on the page looks like this:

var v = new SomeView();
$(something).append(v.render().el);

The v.render() call adds some HTML to the view's el but the el won't be on the page until after the append finishes and that happens after render has completed. So if you have a render like this:

this.$el.html('<span id="pancakes">Pancakes</span>');
var $pancakes = $('#pancakes');

then $pancakes will be empty as #pancakes is inside this.$el but it isn't on that page yet and $('#pancakes') will look on the page.

Back to your code, I'd guess that #custphone and friends come from your template. That means that they'll be in the view's $el but not the page itself when you $('#custphone').mask(...); the result is that you're calling mask on a bunch of empty jQuery objects.

You can use find to look for those elements in the right place:

this.$el.find('#custphone').mask('(999) 999-9999');
//...

or you can use the this.$ function that Backbone sets up for you:

$ (jQuery) view.$(selector)

If jQuery is included on the page, each view has a $ function that runs queries scoped within the view's element. [...] It's equivalent to running: view.$el.find(selector).

So this.$(x) is more or less a short form of this.$el.find(x) and you'd say:

this.$('#custphone').mask('(999) 999-9999');
//...
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Thanks - this "render problem" seems to come up a lot. So View/render() takes my template and uses it to add nodes to the DOM, and in my View/render() I am setting up new DOM items, but if I refer to the current DOM, since my nodes are not present in the instantiated/current HTML, so it was kind of a null reference? – Tom Oct 15 '13 at 17:31
  • Almost. `render` (usually) only puts things into `this.el`, nothing gets into the DOM until someone puts your view's `el` on the page. If you say `this.$('#id')` then you're looking for `#id` inside `this.el`, if you say `$('#id')` then you're looking at the main DOM that is being displayed on the page; if `#id` isn't on the page yet then `$('#id').length` will be zero and you won't be able to do anything useful with it. – mu is too short Oct 15 '13 at 17:58