Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access file input with knockout binding?

Tags:

Given the following code:

<input data-bind="event: { change: uploadImage(this.files[0]) }" style="width: 10px;" type="file"> 

I get an error saying "files is not defined". I'm trying to convert this demo:

https://github.com/paulrouget/miniuploader/blob/gh-pages/index.html

To a knockout-friendly implementation. The error happens when I load the page. Any idea how I can access the file, if it's been specified by the user?

jsfiddle : http://jsfiddle.net/LkqTU/9597/

like image 657
SB2055 Avatar asked Jun 05 '13 03:06

SB2055


People also ask

What is two-way data binding in knockout JS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.

What is binding in Knockout?

Essentially a binding or a data binding is a way to link your ViewModels to your Views(templates) and vice versa. KnockoutJS uses two-way data binding, which means changes to your ViewModel influence the View and changes to your View can influence the ViewModel.


1 Answers

You have two problems:

  • if you just write a function call (uploadImage(this.files[0])) inside an object literal it will be executed once when the object literal is initialized so when KO parses the binding. So it will be executed once with the wrong arguments and you change event won't work. You can make it work with wrapping it into an anonymous function. See in documentation Accessing the event object, or passing more parameters section.

  • the this doesn't refer to the current element in the binding you need to use $element instead.

So the correct binding looks like this:

data-bind="event: { change: function() { uploadImage($element.files[0]) } }" 

Demo JSFiddle.

like image 111
nemesv Avatar answered Sep 16 '22 17:09

nemesv