Monday, September 22, 2014

Add knockout.js in CodeIgniter



CodeIgniter - PHP Model-View-Controller (MVC), can be downloaded from:
https://ellislab.com/codeigniter

knockout.js - JavaScript (MVC) can be downloaded from
http://knockoutjs.com/

Create assests/js folder and copy knockout library  knockout-3.2.0.js to this folder.
Under application/controllers, create test.php
<?php
class Test extends CI_Controller {
    public function index() {
        $this->load->helper('url');
        echo '<h2>Add knockout.js in CodeIgniter</h2>';
        $this->load->view('test');
    }
}
?>

Under applications/views folder, create test.php
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

<p>Full name: <strong data-bind="text: fullName"></strong></p>

<script type="text/javascript" src="<?php echo base_url('assets/js/knockout-3.2.0.js') ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/inputname.js') ?>"></script>
</body>
</html>

Under assests/js folder, create inputname.js
// Here's my data model
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
    this.firstName = ko.observable("Jiansen");
    this.lastName = ko.observable("Lu");

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();   
    }, this);
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());

My case, run: (I create a parent folder MVC0
http://localhost/MVC/CodeIgniter/index.php/test
Video: Add knockout.js in CodeIgniter


1 comment: