Ember.js value binding with HTML5 file upload - javascript

I am not far from it to get the file upload working with Ember-data. But I do not get the value binding right. Below the relevant code.
This is the App.js
App.LandcodeNewRoute = Ember.Route.extend({
model: function () {
return this.store.createRecord('landcode');
},
actions: {
saveLandcode: function () {
this.currentModel.save();
}
}
});
// REST & Model
App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'api'
});
App.Store = DS.Store.extend({
adapter: 'App.ApplicationAdapter'
});
App.Landcode = DS.Model.extend({
code: DS.attr('string'),
image: DS.attr('string')
});
// Views
App.UploadFile = Ember.TextField.extend({
tagName: 'input',
attributeBindings: ['name'],
type: 'file',
change: function (e) {
var reader, that;
that = this;
reader = new FileReader();
reader.onload = function (e) {
var fileToUpload = e.target.result;
console.log(e.target.result); // this spams the console with the image content
console.log(that.get('controller')); // output: Class {imageBinding: Binding,
that.get('controller').set(that.get('name'), fileToUpload);
};
return reader.readAsText(e.target.files[0]);
}
});
HTML
<script type="text/x-handlebars" data-template-name="landcode/new">
Code: {{input value=code}}<br />
Image: {{view App.UploadFile name="image" imageBinding="Landcode.image" }}
<button {{action 'saveLandcode'}}>Save</button>
</script>
As you can see in the HTML part is that I try to bind the imagecontent to the Landcode model attribute image. Tried it also without capital L.
I think I cant bind the image as such, because it is a custom view object? And also normally it would bind automatically I think. Maybe I am just doing some things twice.
References:
http://emberjs.com/api/classes/Ember.Binding.html
http://devblog.hedtek.com/2012/04/brief-foray-into-html5-file-apis.html
File upload with Ember data
How: File Upload with ember.js
http://discuss.emberjs.com/t/file-uploads-is-there-a-better-solution/765
http://chrismeyers.org/2012/06/12/ember-js-handlebars-view-content-inheritance-image-upload-preview-view-object-binding/

I updated your code to the following:
App.LandcodeNewRoute = Ember.Route.extend({
model: function () {
return this.store.createRecord('landcode');
},
actions: {
saveLandcode: function () {
this.currentModel.save();
}
}
});
// REST & Model
App.ApplicationAdapter = DS.RESTAdapter.extend({
namespace: 'api'
});
App.Landcode = DS.Model.extend({
code: DS.attr('string'),
image: DS.attr('string')
});
// views
App.UploadFile = Ember.TextField.extend({
tagName: 'input',
attributeBindings: ['name'],
type: 'file',
file: null,
change: function (e) {
var reader = new FileReader(),
that = this;
reader.onload = function (e) {
var fileToUpload = e.target.result;
Ember.run(function() {
that.set('file', fileToUpload);
});
};
return reader.readAsDataURL(e.target.files[0]);
}
});
In the App.UploadFile instead of reference the controller directlly, I set the file property. So you can bind your model property, with the view using:
{{view App.UploadFile name="image" file=image }}
The Ember.run is used to you don't have problems when testing the app.
Please give a look in that jsfiddle http://jsfiddle.net/marciojunior/LxEsF/
Just fill the inputs and click in the save button. And you will see in the browser console, the data that will be send to the server.

I found that using attaching a data URI to a model attribute didn't allow files more than about 60k to be uploaded. Instead I ended up writing a form data adapter for ember-data. This will upload all the model data using FormData. Sorry that it's in CoffeeScript rather than JS but it's pasted from my blog post. You can read the whole thing at http://blog.mattbeedle.name/posts/file-uploads-in-ember-data/
`import ApplicationAdapter from 'appkit/adapters/application'`
get = Ember.get
FormDataAdapter = ApplicationAdapter.extend
ajaxOptions: (url, type, hash) ->
hash = hash || {}
hash.url = url
hash.type = type
hash.dataType = 'json'
hash.context = #
if hash.data and type != 'GET' and type != 'DELETE'
hash.processData = false
hash.contentType = false
fd = new FormData()
root = Object.keys(hash.data)[0]
for key in Object.keys(hash.data[root])
if hash.data[root][key]
fd.append("#{root}[#{key}]", hash.data[root][key])
hash.data = fd
headers = get(#, 'headers')
if headers != undefined
hash.beforeSend = (xhr) ->
for key in Ember.keys(headers)
xhr.setRequestHeader(key, headers[key])
hash
`export default FormDataAdapter`

Related

Anchoring to an element with a javascript hash router

I'm using Parse-SDK-JS, Handlebars.js and hash routing to create a dynamic webpage. When a user clicks on any link, I call a template using a URL in the following way: http://www.website.com/#/admin.
Router
BlogApp.Router = Parse.Router.extend({
start: function () {
Parse.history.start({root: '/beta/'});
},
routes: {
'': 'index',
'blog/:url': 'blog',
'category/:url': 'category',
'admin': 'admin',
'login': 'login',
'reset': 'reset',
'logout': 'logout',
'add': 'add',
'register': 'register',
'editprofile': 'editprofile',
'changeprofilepic': 'changeprofilepic',
':username': 'userprofile'
},
index: function () {
BlogApp.fn.setPageType('blog');
$blogs = [];
if (!currentUser) {
Parse.history.navigate('#/register', {trigger: true});
console.log("There is no logged in user.");
} else {
var groupId = currentUser.get('groupId');
var designsQuery = new Parse.Query(BlogApp.Models.Blog).equalTo('groupId', groupId).include('author').descending('lastReplyUpdatedAt').limit(50);
designsQuery.find({success: function (blogs) {
for (var i in blogs) {
var des = blogs[i].toJSON();
des.author = blogs[i].get('author').toJSON();
$blogs.push(des);
}
// console.log(blogs);
BlogApp.fn.renderView({
View: BlogApp.Views.Blogs,
data: {blogs: $blogs}
});
}, error: function (blogs, e) {
console.log(JSON.stringify(e));
}});
}
},
});
View
BlogApp.Views.Blogs = Parse.View.extend({
template: Handlebars.compile($('#blogs-tpl').html()),
className: 'blog-post',
render: function () {
var collection = {blog: []};
collection = {blog: this.options.blogs};
this.$el.html(this.template(collection));
},
});
My problem is that upon loading a new template, the user is not sent to the top of the page, i.e. to the following div:
<div id="main-nav"></div>
The users' scroll position on the page doesn't change if the new page is longer than the current page. The user just ends up somewhere down the middle of the page because the new template is loaded but they are not anchoring anywhere new.
Normally in HTML I would open a new page to a particular anchor with something like this: http://www.website.com/page#container if I wanted to, but with the way I set up my hash routing the anchor is the template call itself, so I can't do something like this: http://www.website.com/#/admin#container.
I hope this makes sense.
How can I always send the user to the div "container" upon loading a new template into my view?
I solved this by scrolling into an element after the View was generated.
cookies: function () {
BlogApp.fn.setPageType('cookies');
BlogApp.fn.renderView({
View: BlogApp.Views.Cookies
});
document.getElementById('main-nav').scrollIntoView();
},
Better... by adding the scrollIntoView() function after data is rendered into the View object, so that this works for all links in the router without so much copy pasta.
BlogApp.fn.renderView = function (options) {
var View = options.View, // type of View
data = options.data || null, // data obj to render in the view
$container = options.$container || BlogApp.$container, // container to put the view
notInsert = options.notInsert, // put the el in the container or return el as HTML
view = new View(data);
view.render();
if (notInsert) {
return view.el.outerHTML;
} else {
$container.html(view.el);
document.getElementById('main-nav').scrollIntoView();
}
};

How do i pass a received array into underscore template

I am getting a long array from PHP containing various data objects.
[{"commid":"1","uid":"0","pid":"3","comment":"comm","parid":null,"date":"2016-10-27 15:03:10"},
{"commid":"2","uid":"0","pid":"10","comment":"Ana","parid":null,"date":"2016-10-27 15:03:51"},
{"commid":"3","uid":"0","pid":"5","comment":"asss!","parid":null,"date":"2016-10-27 15:05:50"},
{"commid":"4","uid":"0","pid":"10","comment":"Lawl?","parid":null,"date":"2016-10-27 17:03:59"},
{"commid":"5","uid":"0","pid":"14","comment":"sd","parid":null,"date":"2016-11-06 00:25:04"},
{"commid":"6","uid":"0","pid":"14","comment":"sds","parid":null,"date":"2016-11-06 00:25:50"},
{"commid":"7","uid":"0","pid":"14","comment":"WOW!","parid":null,"date":"2016-11-08 15:06:18"},
{"commid":"8","uid":"0","pid":"13","comment":"Hello!?","parid":null,"date":"2016-11-08 15:14:30"}]
My Backbone View which will be rendering the data is
var WorkPage = Backbone.View.extend({
el: $('#indexcontent'),
render: function() {
Backbone.history.navigate('work');
var _this = this;
this.$el.html(workHTML);
$.ajax({
type: "GET",
url: "includes/server_api.php/work",
data: '',
cache: false,
success: function(html) {
console.log(html);
var compiledTemplate = _.template($('#content-box').html(), html);
_this.$el.html(compiledTemplate);
},
error: function(e) {
console.log(e);
}
});
return false;
}
});
My workHTML which will be rendered by Underscore is
<script type="text/template" id="content-box">
<div class="workhead">
<h3 class="msg comment"><%= comment%></h3>
<p class="date"><%= date%></p>
</div>
</script>
<div id="content-box-output"></div>
How do I implement a underscore loop here?
You should take advantage of Backbone's features. And to do that, you need to understand how to use a REST API with Backbone.
Backbone's Model is made to manage a single object and handle the communication with the API (GET, POST, PATCH, PUT requests).
Backbone's Collection role is to handle an array of model, it handles fetching it (GET request that should return a JSON array of objects) and it also parse each object into a Backbone Model by default.
Instead of hard-coding a jQuery ajax call, use a Backbone collection.
var WorkCollection = Backbone.Collection.extend({
url: "includes/server_api.php/work",
});
Then, modularize your views. Make an item view for each object of the array you received.
var WorkItem = Backbone.View.extend({
// only compile the template once
template: _.template($('#content-box').html()),
render: function() {
// this is how you pass data to the template
this.$el.html(this.template(this.model.toJSON()));
return this; // always return this in the render function
}
});
Then your list view looks like this:
var WorkPage = Backbone.View.extend({
initialize: function(options) {
this.itemViews = [];
this.collection = new WorkCollection();
this.listenTo(this.collection, 'reset', this.render);
// this will make a GET request to
// includes/server_api.php/work
// expecting a JSON encoded array of objects
this.collection.fetch({ reset: true });
},
render: function() {
this.$el.empty();
this.removeItems();
this.collection.each(this.renderItem, this);
return this;
},
renderItem: function(model) {
var view = new WorkItem({
model: model
});
this.itemViews.push(view);
this.$el.append(view.render().el);
},
// cleanup to avoid memory leaks
removeItems: function() {
_.invoke(this.itemViews, 'remove');
this.itemViews = [];
}
});
It's unusual to set the url in the render function, you should keep the responsibilities scoped to the right place.
The router could be something like:
var Router = Backbone.Router.extend({
routes: {
'work': 'workPage'
},
workPage: function() {
var page = new WorkPage({
el: $('#indexcontent'),
});
}
});
Then, if you want to see the work page:
var myRouter = new Router();
Backbone.history.start();
myRouter.navigate('#work', { trigger: true });
Templates and RequireJS
My index.html page contains this
indexcontent div but the content-box which contains the template
format which we are compiling is stored in different work.html. So,
if i dont load this work.html in my main index.html i am unable to
access content-box.
I would recommend to use the text require.js plugin and load each template for the view like this:
The work-item.js file:
define([
'underscore', 'backbone',
'text!templates/work-item.html',
], function(_, Backbone, WorkItemTemplate) {
var WorkItem = Backbone.View.extend({
template: _.template(WorkItemTemplate),
/* ...snip... */
});
return WorkItem;
});
The work-page.js file:
define([
'underscore', 'backbone',
'text!templates/work-page.html',
], function(_, Backbone, WorkPageTemplate) {
var WorkPage = Backbone.View.extend({
template: _.template(WorkPageTemplate),
});
return WorkPage;
});
In your index.html file you need to have _.each() method to iterate throught each element
<% _.each(obj, function(elem){ %>
<div class="workhead">
<h3 class="msg comment"><%= elem.comment %></h3>
<p class="date"><%= elem.date%></p>
</div>
<% }) %>
I make variable of your response just to have data to work with. In your View you need to set point on template
template: _.template($("#content-box").html()), and in render method just send data as object.
Here is working code : jsFiddle
Here is one way to load the template for each value in the data array.
var WorkPage = Backbone.View.extend({
el: $('#indexcontent'),
render: function() {
Backbone.history.navigate('work');
var _this = this;
this.$el.html(workHTML);
$.ajax({
type: "GET",
url: "includes/server_api.php/work",
data: '',
cache: false,
success: function(data) {
console.log(data);
var $div = $('<div></div>');
_.each(data, function(val) {
$div.append(_.template($('#content-box').html(), val));
});
_this.$el.html($div.html());
},
error: function(e) {
console.log(e);
}
});
return false;
}
});

Model method error while trying to navigate

I have several Backbone Models rendered in a Collection View, and also I have a route that should render a view of that model. So, here come the views
resume.js
// this renders a single model for a collection view
var ResumeView = Backbone.View.extend({
model: new Resume(),
initialize: function () {
this.template = _.template($('#resume').html());
},
render: function () {
this.$el.html(this.template(this.model.toJSON));
return this;
}
});
#resume template
<section id="resume">
<h1><%= profession %></h1>
<!-- !!!!! The link for a router which should navigate to ShowResume view -->
View Details
</section>
Collection view:
var ResumeList = Backbone.View.extend({
initialize: function (options) {
this.collection = options.collection;
this.collection.on('add', this.render, this);
// Getting the data from JSON-server
this.collection.fetch({
success: function (res) {
_.each(res.toJSON(), function (item) {
console.log("GET a model with " + item.id);
});
},
error: function () {
console.log("Failed to GET");
}
});
},
render: function () {
var self = this;
this.$el.html('');
_.each(this.collection.toArray(), function (cv) {
self.$el.append((new ResumeView({model: cv})).render().$el);
});
return this;
}
});
The code above works perfectly and does exactly what I need -- an array of models is fetched from my local JSON-server and each model is displayed within a collection view. However, the trouble starts when I try to navigate through my link in the template above. Here comes the router:
var AppRouter = Backbone.Router.extend({
routes: {
'': home,
'resumes/:id': 'showResume'
},
initialize: function (options) {
// layout is set in main.js
this.layout = options.layout
},
home: function () {
this.layout.render(new ResumeList({collection: resumes}));
},
showResume: function (cv) {
this.layout.render(new ShowResume({model: cv}));
}
});
and finally the ShowResume view:
var ShowResume = Backbone.View.extend({
initialize: function (options) {
this.model = options.model;
this.template = _.template($('#full-resume').html());
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
}
});
I didn't provide the template for this view because it is quite large, but the error is following: whenever I try to navigate to a link, a view tries to render, but returns me the following error: Uncaught TypeError: this.model.toJSON is not a function. I suspect that my showResume method in router is invalid, but I can't actually get how to make it work in right way.
You are passing the string id of the url 'resumes/:id' as the model of the view.
This should solve it.
showResume: function (id) {
this.layout.render(new ShowResume({
model: new Backbone.Model({
id: id,
profession: "teacher" // you can pass data like this
})
}));
}
But you should fetch the data in the controller and react accordingly in the view.
var AppRouter = Backbone.Router.extend({
routes: {
'*otherwise': 'home', // notice the catch all
'resumes/:id': 'showResume'
},
initialize: function(options) {
// layout is set in main.js
this.layout = options.layout
},
home: function() {
this.layout.render(new ResumeList({ collection: resumes }));
},
showResume: function(id) {
// lazily create the view and keep it
if (!this.showResume) {
this.showResume = new ShowResume({ model: new Backbone.Model() });
}
// use the view's model and fetch
this.showResume.model.set('id', id).fetch({
context: this,
success: function(){
this.layout.render(this.showResume);
}
})
}
});
Also, this.model = options.model; is unnecessary as Backbone automatically picks up model, collection, el, id, className, tagName, attributes and events, extending the view with them.

Ember.js File Upload to change model on a route

I have Ember displaying a list of things.
I want the user to upload a file and change the list of things to the stuff in that file.
HTML
<script type="text/x-handlebars" id="index">
<h2>List of things</h2>
<ul>
{{#each item in model}}
<li>{{item}}</li>
{{/each}}
</ul>
Change List of Things:
{{#view Ember.View}}
{{view App.FileUp}}
{{/view}}
</script>
Javascript
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
});
App.ApplicationController = Ember.Controller.extend({
actions: {
file_upload: function(data) {
alert("I want to change the model to: " + data);
}
}
});
App.FileUp= Ember.TextField.extend({
type: 'file',
change: function(evt) {
var input = evt.target;
if (input.files && input.files[0]) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var c = App.ApplicationController.create();
c.send('file_upload', data);
}
reader.readAsText(input.files[0]);
}
},
});
At the line with the alert, I have access to the text from the uploaded file, and I'm in the application controller. How can I change the model so that the list of the page reflects what's in the text file?
JS Fiddle: http://jsfiddle.net/LJx9t/
If this code isn't idiomatic Ember, please feel free to correct.
Being a component you should use sendAction to pass the action out of the component. This allows the component to be used multiple times and doesn't tie it to the context.
{{view App.FileUp uploadComplete='file_upload'}}
{{view App.FileUp uploadComplete='file_upload2'}}
Then inside your component
change: function(evt) {
var input = evt.target,
self = this;
if (input.files && input.files[0]) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
self.sendAction('uploadComplete', data);
}
reader.readAsText(input.files[0]);
}
},
then your action gets sent to the controller, then route, then up the route tree until it's handled.
Create an index controller to handle it
App.IndexController = Ember.Controller.extend({
actions: {
file_upload: function(data) {
this.set('model', data.split('\n'));
},
file_upload2: function(data) {
alert(data);
}
}
});
http://jsfiddle.net/rmCYk/1/
The model you want to change has been created by the IndexRoute, so you need to set it to the IndexController. Furthermore the App.FileUp is a component, so in order to send the action to the currently active controller, which is IndexControler it is required to use targetObject or get('controller') from parentView .
(related info, https://github.com/emberjs/ember.js/blob/master/packages/ember-handlebars/lib/controls.js#L81-84 and a discussion https://github.com/emberjs/ember.js/issues/3393 )
So assuming a file with csv is uploaded the following code can achieve what you require,
http://jsfiddle.net/9u3Cd/
js
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return ['red', 'yellow', 'blue'];
}
});
App.IndexController = Ember.ObjectController.extend({
actions: {
file_upload: function(data) {
alert("I want to change the model to: " + data);
this.set('model',data.split(","));
}
}
});
App.FileUp= Ember.TextField.extend({
type: 'file',
change: function(evt) {
var self = this;
var input = evt.target;
if (input.files && input.files[0]) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
//self.get('parentView').get('controller').send('file_upload', data);
self.get('targetObject').send('file_upload', data);
}
reader.readAsText(input.files[0]);
}
},
});

Re-render a view

What is the best way to re-render a view after an event takes place (eg. submitting a note). In the below code, I want to re-render the view to show the note that was just added.
var NotesView = SectionBaseView.extend({
model: app.models.Note,
events: {
'submit': 'Notes'
},
Notes: function (e) {
e.preventDefault();
var details = new this.model($('form').serializeObject());
details.url = '/email/Notes';
details
.save()
.done(function () {
app.notifySuccess('Note added successfully.');
});
views['#Notes'].render();
}
});
Notes view is initialized in the document.ready function as follows:
views['#Notes'] = new NotesView({ el: '#Notes', template: app.templates.Notes });
I tried using views['#Notes'].render(); but this doesn't seem to be working.
The default implementation of render is a no-op. Override this function with your code that renders the view template from model data, and updates this.el with the new HTML. A good convention is to return this at the end of render to enable chained calls. Docs
var NotesView = SectionBaseView.extend({
model: app.models.Note,
events: {
'submit': 'Notes'
},
render : function(){
//your code
return this;
},
Notes: function (e) {
var that = this;
e.preventDefault();
var details = new this.model($('form').serializeObject());
details.url = '/email/Notes';
details
.save()
.done(function () {
app.notifySuccess('Note added successfully.');
});
that.render();
}
});
on document.ready
views['#Notes'] = new NotesView({ el: '#Notes', template: app.templates.Notes });
views['#Notes'].render();

Categories