2018年2月22日 星期四

ConnectDB

<?php

interface ConnectDB {

    public function connect($database); // 連線

    public function selectDB($database);

    public function query($sql);

    public function fetchArray(); // 返回陣列

    public function fetchObjArray(); // 返回物件

    public function fetchOneArray($column = FALSE);

    public function fetchKeyArray($keyWord = null);

    public function Insert2DB($sql); // 專門用於插入資料用(會返回 insert_id)

    public function getInsertId();

    public function freeResult(); // 釋放結果的記憶體

    public function closeConnect();

    public function autoCommit($option);

    public function getConnect(); // 返回連線

    public function getResult(); // 返回查詢結果

    public function getColumn(); // 返回所有查詢後的欄位

    public function numOfRows();
}

?>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ConnectDBMyli
 *
 * @author test
 */
class ConnectDBMyli implements ConnectDB {

    protected $insert_id;
    protected $user;
    protected $psw;
    protected $url;
    protected $dataBase;
    protected $conn;
    protected $result;
    protected $errorMsg;

    /* ---------------------------------------------------------------------- */

    public function __construct() {
       
    }

    /* ---------------------------------------------------------------------- */

    public function setUser($user) {
        $this->user = $user;
    }

    /* ====================================================================== */

    public function setPsw($psw) {
        $this->psw = $psw;
    }

    /* ====================================================================== */

    public function setUrl($url) {
        $this->url = $url;
    }

    /* ====================================================================== */

    public function connect($database, $url = NULL, $user = NULL, $psw = NULL) {
        if ($url) {
            $this->setUrl($url);
        }

        if ($user) {
            $this->setUser($user);
        }

        if ($psw) {
            $this->setPsw($psw);
        }
        /* ------------------------------------------ */
        $this->dataBase = $database;

        $this->conn = @new mysqli($this->url, $this->user, $this->psw, $this->dataBase);

        if (mysqli_connect_errno() != 0) {

            $this->errorMsg = sprintf("connect error: %s", mysqli_connect_error());

            throw new Exception($this->errorMsg);
        }
        /* ------------------------------------------ */

        if (!($this->result = @$this->conn->query("SET NAMES 'utf8'"))) {

            $this->errorMsg = sprintf("set names error: %s", $this->conn->error);

            // throw new Exception($this->errorMsg);
        }
    }

    /* ====================================================================== */

    /**
     * 在建立連結之後,選擇 dataBase
     *
     * {@inheritDoc}
     * @see ConnectDB::selectDB()
     */
    public function selectDB($database) {
        $conn = $this->conn;

        $conn->select_db($database);
    }

    /* ====================================================================== */

    /**
     * 查詢
     *
     * {@inheritDoc}
     * @see ConnectDB::query()
     */
    public function query($sql) {
        $conn = $this->conn;


        if (!($this->result = $conn->query($sql))) {

            $this->errorMsg = sprintf("query error: %s", $this->conn->error);

            throw new Exception($this->errorMsg);
        }
    }

    /* ====================================================================== */

    public function fetchArray() {
        $data_arry = array();

        $result = $this->result;

        while (($row_data = $result->fetch_array()) !== null) {
           
           
            $data_arry[] = $row_data;
        }
    
        return $data_arry;
    }

    /* ====================================================================== */

    public function fetchObjArray() {
        $data_arry = array();

        $result = $this->result;

        while (($obj = $result->fetch_object()) !== null) {
            $data_arry[] = $obj;
        }

        return $data_arry;
    }

    /* ====================================================================== */

    /**
     * 只取出一個欄位的值
     */
    public function fetchOneColumnArray($column = FALSE) {
        $data_arry = array();
        $result = $this->result;
        $column = strtolower($column);


        while (($row_data = $result->fetch_array()) !== null) {

            foreach ($row_data as $k => $v) {
                if ($column === strtolower($k)) {

                    $data_arry[] = $v;
                }
            }
        }

        $this->freeResult();

        return $data_arry;
    }

    /* ====================================================================== */

    public function Insert2DB($sql) {
        $conn = $this->conn;

        if (!($this->result = $conn->query($sql))) {
            $this->errorMsg = sprintf("query error: %s", $this->conn->error);
            throw new Exception($this->errorMsg);
        }

        $insert_id = $conn->insert_id;

        $this->freeResult();

        return $insert_id;
    }

    /* ====================================================================== */

    public function autoCommit($option) {
       
    }

    /* ====================================================================== */

    public function closeConnect() {
        $this->conn->close();
    }

    /* ---------------------------------------------------------------------- */

    public function fetchKeyArray($keyWord = null) {
        $result_array = array();
        $result = $this->result;

        if ($keyWord === null) {
            // 若沒有給 key,則用預設的查詢回應
            $result_array = fetchArray();
        } else {
            while (($row_data = $result->fetch_array()) !== null) {

                if (isset($row_data[$keyWord])) {
                    $result_array[$row_data[$keyWord]] = $row_data;
                }
            }
        }

        return $result_array;
    }

    /* ---------------------------------------------------------------------- */

    public function fetchOneArray($column = FALSE) {
        $result = $this->result;

        $row_data = $result->fetch_array();

        if ($column) {
            return $row_data[$column];
        }

        $this->freeResult();

        return $row_data;
    }

    /* ---------------------------------------------------------------------- */

    public function freeResult() {
        $this->result->close();
    }

    /* ---------------------------------------------------------------------- */

    public function getInsertId() {
        $conn = $this->conn;

        return $conn->insert_id;
    }

    /* ---------------------------------------------------------------------- */

    public function getConnect() {
       
    }

    /* ---------------------------------------------------------------------- */

    public function getResult() {
       
    }

    /* ---------------------------------------------------------------------- */

    public function getColumn() {
        $column_array = array();
        $result = $this->result;

        $column_array = $result->fetch_field();

        return $column_array;
    }

    public function numOfRows() {
        $result = $this->result;
        return $result->num_rows;
    }

}

2018年1月26日 星期五

HTML 事件属性

Window 事件屬性

針對 window 對象觸發的事件(應用到 <body> 標籤):
屬性描述
onafterprintscript文檔打印之後運行的腳本。
onbeforeprintscript文檔打印之前運行的腳本。
onbeforeunloadscript文檔卸載之前運行的腳本。
onerrorscript在錯誤發生時運行的腳本。
onhaschangescript當文檔已改變時運行的腳本。
onloadscript頁面結束加載之後觸發。
onmessagescript在消息被觸發時運行的腳本。
onofflinescript當文檔離線時運行的腳本。
ononlinescript當文檔上線時運行的腳本。
onpagehidescript當窗口隱藏時運行的腳本。
onpageshowscript當窗口成為可見時運行的腳本。
onpopstatescript當窗口歷史記錄改變時運行的腳本。
onredoscript當文檔執行撤銷(redo)時運行的腳本。
onresizescript當瀏覽器窗口被調整大小時觸發。
onstoragescript在 Web Storage 區域更新後運行的腳本。
onundoscript在文檔執行 undo 時運行的腳本。
onunloadscript一旦頁面已下載時觸發(或者瀏覽器窗口已被關閉)。

Form 事件

由 HTML 表單內的動作觸發的事件(應用到幾乎所有 HTML 元素,但最常用在 form 元素中):
屬性描述
onblurscript元素失去焦點時運行的腳本。
onchangescript在元素值被改變時運行的腳本。
oncontextmenuscript當上下文菜單被觸發時運行的腳本。
onfocusscript當元素獲得焦點時運行的腳本。
onformchangescript在表單改變時運行的腳本。
onforminputscript當表單獲得用戶輸入時運行的腳本。
oninputscript當元素獲得用戶輸入時運行的腳本。
oninvalidscript當元素無效時運行的腳本。
onresetscript當表單中的重置按鈕被點擊時觸發。HTML5 中不支持。
onselectscript在元素中文本被選中後觸發。
onsubmitscript在提交表單時觸發。

Keyboard 事件

屬性描述
onkeydownscript在用戶按下按鍵時觸發。
onkeypressscript在用戶敲擊按鈕時觸發。
onkeyupscript當用戶釋放按鍵時觸發。

Mouse 事件

由鼠標或類似用戶動作觸發的事件:
屬性描述
onclickscript元素上發生鼠標點擊時觸發。
ondblclickscript元素上發生鼠標雙擊時觸發。
ondragscript元素被拖動時運行的腳本。
ondragendscript在拖動操作末端運行的腳本。
ondragenterscript當元素元素已被拖動到有效拖放區域時運行的腳本。
ondragleavescript當元素離開有效拖放目標時運行的腳本。
ondragoverscript當元素在有效拖放目標上正在被拖動時運行的腳本。
ondragstartscript在拖動操作開端運行的腳本。
ondropscript當被拖元素正在被拖放時運行的腳本。
onmousedownscript當元素上按下鼠標按鈕時觸發。
onmousemovescript當鼠標指針移動到元素上時觸發。
onmouseoutscript當鼠標指針移出元素時觸發。
onmouseoverscript當鼠標指針移動到元素上時觸發。
onmouseupscript當在元素上釋放鼠標按鈕時觸發。
onmousewheelscript當鼠標滾輪正在被滾動時運行的腳本。
onscrollscript當元素滾動條被滾動時運行的腳本。

Media 事件

由媒介(比如視頻、圖像和音頻)觸發的事件(適用於所有 HTML 元素,但常見於媒介元素中,比如 <audio>、<embed>、<img>、<object> 以及 <video>):
屬性描述
onabortscript在退出時運行的腳本。
oncanplayscript當文件就緒可以開始播放時運行的腳本(緩衝已足夠開始時)。
oncanplaythroughscript當媒介能夠無需因緩衝而停止即可播放至結尾時運行的腳本。
ondurationchangescript當媒介長度改變時運行的腳本。
onemptiedscript當發生故障並且文件突然不可用時運行的腳本(比如連接意外斷開時)。
onendedscript當媒介已到達結尾時運行的腳本(可發送類似「感謝觀看」之類的消息)。
onerrorscript當在文件加載期間發生錯誤時運行的腳本。
onloadeddatascript當媒介數據已加載時運行的腳本。
onloadedmetadatascript當元數據(比如分辨率和時長)被加載時運行的腳本。
onloadstartscript在文件開始加載且未實際加載任何數據前運行的腳本。
onpausescript當媒介被用戶或程序暫停時運行的腳本。
onplayscript當媒介已就緒可以開始播放時運行的腳本。
onplayingscript當媒介已開始播放時運行的腳本。
onprogressscript當瀏覽器正在獲取媒介數據時運行的腳本。
onratechangescript每當回放速率改變時運行的腳本(比如當用戶切換到慢動作或快進模式)。
onreadystatechangescript每當就緒狀態改變時運行的腳本(就緒狀態監測媒介數據的狀態)。
onseekedscript當 seeking 屬性設置為 false(指示定位已結束)時運行的腳本。
onseekingscript當 seeking 屬性設置為 true(指示定位是活動的)時運行的腳本。
onstalledscript在瀏覽器不論何種原因未能取回媒介數據時運行的腳本。
onsuspendscript在媒介數據完全加載之前不論何種原因終止取回媒介數據時運行的腳本。
ontimeupdatescript當播放位置改變時(比如當用戶快進到媒介中一個不同的位置時)運行的腳本。
onvolumechangescript每當音量改變時(包括將音量設置為靜音)時運行的腳本。
onwaitingscript當媒介已停止播放但打算繼續播放時(比如當媒介暫停已緩衝更多數據)運行腳本

拖曳一個小方塊

<body>
    <div id="t_1">
        <div class="box">

        </div>
    </div>
</body>
<script>
        $(document).ready(function () {

            $('div.box').on('mousedown', function (e) {
                let t1 = e.target;
                let x = e.offsetX;
                let y = e.offsetY;

                $('#t_1').on('mousemove', function (e) {
                    let t2 = e.target;
                    let _x = e.offsetX;
                    let _y = e.offsetY;

                    if (e.target.isEqualNode(e.currentTarget)) {
                        // console.log(_x);

                        $(t1).css({
                            left: (_x - x),
                            top: (_y - y)
                        });
                    }
                });
            });

            $('#t_1').on('mouseup', function (e) {
                $('#t_1').off('mousemove');
            });

        });
    </script>

2018年1月1日 星期一

html_edit

https://kevinroth.com/rte/
http://unverse.net/Whizzywig-web-based-rich-text-editor

2017年12月29日 星期五

GreenBackbone view 的 ajax(template | component)


--------------------------------------------------------------------------
// component的例子
<div>
    {{x}}
</div>
<script>
    // 把上面的 html內容傳進 fun
    function(template) {
        return Backbone.BForView.extend({
            templateContent: template
        });
    }
</script>
--------------------------------------------------------------------------
// template的例子
<div>
    {{x}}
</div>
<script>
    function(view) {
          // template mounted
    }
</script>
<script>
    function(view) {
          // template removed    }
</script>
 --------------------------------------------------------------------------
// template 改進
<div>
    {{x}}
</div>
<script>
  
    function() {
         return {
               mounted: fun(view),
               unmouted: fun(view)
              }
    }
</script>

 --------------------------------------------------------------------------

2017年12月23日 星期六

Backbone.Reactive 重要的例子

var d_1 = [{
            age: 12,
            selected: true
        }, {
            age: 1,
            selected: false
        }, {
            age: 2,
            selected: false
        }];
        var d_2 = Backbone.Reactive(d_1, {
            link: function(parent, child) {

                parent.listenTo(child, 'all', function(e, event, options) {
                    debugger;
                    var info = 'parent => ' + event + '|' + JSON.stringify(arguments);

                    for (var i = 0; i < this.value.length; i++) {
                        debugger;
                        var v = this.value[i];
                        var ob = v._bc_ob_;

                        if (v._bc_ob_.cid !== e.target.cid) {
                            ob.triggerOptions = {
                                exclude: [this] // 防止事件無窮回圈
                            }
                            v.selected = false;
                        }
                    }

                    $('#msg_1').html(JSON.stringify(this));
                })
            }
        });
        /*--------------------------*/

        d_2._bc_ob_.on('change', function() {
            var info = 'parent => ' + event + '|' + JSON.stringify(arguments);
            alert(info);
        });

        function set() {

            var index = Math.floor(Math.random() * d_2.length);
            index = (index >= d_2.length ? (d_2.length - 1) : index);
            d_2[index].selected = true;
        }

2017年12月22日 星期五

javascript Map

Properties   
    Map.prototype.size   

Methods
    Map.prototype.clear()

    Map.prototype.delete()

    Map.prototype.entries()

    Map.prototype.forEach()

    Map.prototype.get()

    Map.prototype.has()

    Map.prototype.keys()

    Map.prototype.set()

    Map.prototype.values()

    Map.prototype[@@iterator]()
-----------------------------------------------------------------

範例

區段

使用 Map 物件

區段

var myMap = new Map();

var keyString = 'a string',
    keyObj = {},
    keyFunc = function() {};

// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, 'value associated with keyObj');
myMap.set(keyFunc, 'value associated with keyFunc');

myMap.size; // 3

// getting the values
myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

myMap.get('a string');   // "value associated with 'a string'"
                         // because keyString === 'a string'
myMap.get({});           // undefined, because keyObj !== {}
myMap.get(function() {}) // undefined, because keyFunc !== function () {}

使用 NaN 作為 Map 的鍵

區段

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other:
var myMap = new Map();
myMap.set(NaN, 'not a number');

myMap.get(NaN); // "not a number"

var otherNaN = Number('foo');
myMap.get(otherNaN); // "not a number"

透過 for..of 迭代 Maps

區段

Maps can be iterated using a for..of loop:
var myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
for (var [key, value] of myMap) {
  console.log(key + ' = ' + value);
}
// 0 = zero
// 1 = one

for (var key of myMap.keys()) {
  console.log(key);
}
// 0
// 1

for (var value of myMap.values()) {
  console.log(value);
}
// zero
// one

for (var [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value);
}
// 0 = zero
// 1 = one

透過 forEach() 迭代 Maps

區段

Maps can be iterated using the forEach() method:
myMap.forEach(function(value, key) {
  console.log(key + ' = ' + value);
});
// Will show 2 logs; first with "0 = zero" and second with "1 = one"

與 Array 物件關聯

區段

var kvArray = [['key1', 'value1'], ['key2', 'value2']];

// Use the regular Map constructor to transform a 2D key-value Array into a map
var myMap = new Map(kvArray);

myMap.get('key1'); // returns "value1"

// Use the Array.from function to transform a map into a 2D key-value Array
console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray

// Or use the keys or values iterators and convert them to an array
console.log(Array.from(myMap.keys())); // Will show ["key1", "key2"]

2017年12月5日 星期二

js 筆記

let x = 1;

      y = (++x, ++x);
      console.log(y);

y=3
-----------------------------------------------------------------------------
js 基本類型

boolean, number, string, undefined
null is object
-----------------------------------------------------------------------------

js一些預設方法

 

string.slice(s, e), array.slice(s, e) => slice(切片) 

string.split(符號) 分割成 array => split (分裂)

array.splice(s, l, data_1, data_2)=>splice (拼接)



string.match() => //正則是否用/g差別很大,/g將不顯示捕獲組,但會將符合的化為 array
regular.exec()